1 //===--- TargetInfo.cpp - Information about Target machine ----------------===//
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 TargetInfo and TargetInfoImpl interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/TargetInfo.h"
15 #include "clang/Basic/AddressSpaces.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include <cstdlib>
22 using namespace clang;
23 
24 static const LangAS::Map DefaultAddrSpaceMap = { 0 };
25 
26 // TargetInfo Constructor.
27 TargetInfo::TargetInfo(const llvm::Triple &T) : TargetOpts(), Triple(T) {
28   // Set defaults.  Defaults are set for a 32-bit RISC platform, like PPC or
29   // SPARC.  These should be overridden by concrete targets as needed.
30   BigEndian = true;
31   TLSSupported = true;
32   NoAsmVariants = false;
33   PointerWidth = PointerAlign = 32;
34   BoolWidth = BoolAlign = 8;
35   IntWidth = IntAlign = 32;
36   LongWidth = LongAlign = 32;
37   LongLongWidth = LongLongAlign = 64;
38   SuitableAlign = 64;
39   MinGlobalAlign = 0;
40   HalfWidth = 16;
41   HalfAlign = 16;
42   FloatWidth = 32;
43   FloatAlign = 32;
44   DoubleWidth = 64;
45   DoubleAlign = 64;
46   LongDoubleWidth = 64;
47   LongDoubleAlign = 64;
48   LargeArrayMinWidth = 0;
49   LargeArrayAlign = 0;
50   MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 0;
51   MaxVectorAlign = 0;
52   SizeType = UnsignedLong;
53   PtrDiffType = SignedLong;
54   IntMaxType = SignedLongLong;
55   UIntMaxType = UnsignedLongLong;
56   IntPtrType = SignedLong;
57   WCharType = SignedInt;
58   WIntType = SignedInt;
59   Char16Type = UnsignedShort;
60   Char32Type = UnsignedInt;
61   Int64Type = SignedLongLong;
62   SigAtomicType = SignedInt;
63   ProcessIDType = SignedInt;
64   UseSignedCharForObjCBool = true;
65   UseBitFieldTypeAlignment = true;
66   UseZeroLengthBitfieldAlignment = false;
67   ZeroLengthBitfieldBoundary = 0;
68   HalfFormat = &llvm::APFloat::IEEEhalf;
69   FloatFormat = &llvm::APFloat::IEEEsingle;
70   DoubleFormat = &llvm::APFloat::IEEEdouble;
71   LongDoubleFormat = &llvm::APFloat::IEEEdouble;
72   DescriptionString = "E-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-"
73                       "i64:64:64-f32:32:32-f64:64:64-n32";
74   UserLabelPrefix = "_";
75   MCountName = "mcount";
76   RegParmMax = 0;
77   SSERegParmMax = 0;
78   HasAlignMac68kSupport = false;
79 
80   // Default to no types using fpret.
81   RealTypeUsesObjCFPRet = 0;
82 
83   // Default to not using fp2ret for __Complex long double
84   ComplexLongDoubleUsesFP2Ret = false;
85 
86   // Default to using the Itanium ABI.
87   TheCXXABI.set(TargetCXXABI::GenericItanium);
88 
89   // Default to an empty address space map.
90   AddrSpaceMap = &DefaultAddrSpaceMap;
91 
92   // Default to an unknown platform name.
93   PlatformName = "unknown";
94   PlatformMinVersion = VersionTuple();
95 }
96 
97 // Out of line virtual dtor for TargetInfo.
98 TargetInfo::~TargetInfo() {}
99 
100 /// getTypeName - Return the user string for the specified integer type enum.
101 /// For example, SignedShort -> "short".
102 const char *TargetInfo::getTypeName(IntType T) {
103   switch (T) {
104   default: llvm_unreachable("not an integer!");
105   case SignedChar:       return "char";
106   case UnsignedChar:     return "unsigned char";
107   case SignedShort:      return "short";
108   case UnsignedShort:    return "unsigned short";
109   case SignedInt:        return "int";
110   case UnsignedInt:      return "unsigned int";
111   case SignedLong:       return "long int";
112   case UnsignedLong:     return "long unsigned int";
113   case SignedLongLong:   return "long long int";
114   case UnsignedLongLong: return "long long unsigned int";
115   }
116 }
117 
118 /// getTypeConstantSuffix - Return the constant suffix for the specified
119 /// integer type enum. For example, SignedLong -> "L".
120 const char *TargetInfo::getTypeConstantSuffix(IntType T) {
121   switch (T) {
122   default: llvm_unreachable("not an integer!");
123   case SignedChar:
124   case SignedShort:
125   case SignedInt:        return "";
126   case SignedLong:       return "L";
127   case SignedLongLong:   return "LL";
128   case UnsignedChar:
129   case UnsignedShort:
130   case UnsignedInt:      return "U";
131   case UnsignedLong:     return "UL";
132   case UnsignedLongLong: return "ULL";
133   }
134 }
135 
136 /// getTypeWidth - Return the width (in bits) of the specified integer type
137 /// enum. For example, SignedInt -> getIntWidth().
138 unsigned TargetInfo::getTypeWidth(IntType T) const {
139   switch (T) {
140   default: llvm_unreachable("not an integer!");
141   case SignedChar:
142   case UnsignedChar:     return getCharWidth();
143   case SignedShort:
144   case UnsignedShort:    return getShortWidth();
145   case SignedInt:
146   case UnsignedInt:      return getIntWidth();
147   case SignedLong:
148   case UnsignedLong:     return getLongWidth();
149   case SignedLongLong:
150   case UnsignedLongLong: return getLongLongWidth();
151   };
152 }
153 
154 TargetInfo::IntType TargetInfo::getIntTypeByWidth(
155     unsigned BitWidth, bool IsSigned) const {
156   if (getCharWidth() == BitWidth)
157     return IsSigned ? SignedChar : UnsignedChar;
158   if (getShortWidth() == BitWidth)
159     return IsSigned ? SignedShort : UnsignedShort;
160   if (getIntWidth() == BitWidth)
161     return IsSigned ? SignedInt : UnsignedInt;
162   if (getLongWidth() == BitWidth)
163     return IsSigned ? SignedLong : UnsignedLong;
164   if (getLongLongWidth() == BitWidth)
165     return IsSigned ? SignedLongLong : UnsignedLongLong;
166   return NoInt;
167 }
168 
169 TargetInfo::RealType TargetInfo::getRealTypeByWidth(unsigned BitWidth) const {
170   if (getFloatWidth() == BitWidth)
171     return Float;
172   if (getDoubleWidth() == BitWidth)
173     return Double;
174 
175   switch (BitWidth) {
176   case 96:
177     if (&getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended)
178       return LongDouble;
179     break;
180   case 128:
181     if (&getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble ||
182         &getLongDoubleFormat() == &llvm::APFloat::IEEEquad)
183       return LongDouble;
184     break;
185   }
186 
187   return NoFloat;
188 }
189 
190 /// getTypeAlign - Return the alignment (in bits) of the specified integer type
191 /// enum. For example, SignedInt -> getIntAlign().
192 unsigned TargetInfo::getTypeAlign(IntType T) const {
193   switch (T) {
194   default: llvm_unreachable("not an integer!");
195   case SignedChar:
196   case UnsignedChar:     return getCharAlign();
197   case SignedShort:
198   case UnsignedShort:    return getShortAlign();
199   case SignedInt:
200   case UnsignedInt:      return getIntAlign();
201   case SignedLong:
202   case UnsignedLong:     return getLongAlign();
203   case SignedLongLong:
204   case UnsignedLongLong: return getLongLongAlign();
205   };
206 }
207 
208 /// isTypeSigned - Return whether an integer types is signed. Returns true if
209 /// the type is signed; false otherwise.
210 bool TargetInfo::isTypeSigned(IntType T) {
211   switch (T) {
212   default: llvm_unreachable("not an integer!");
213   case SignedChar:
214   case SignedShort:
215   case SignedInt:
216   case SignedLong:
217   case SignedLongLong:
218     return true;
219   case UnsignedChar:
220   case UnsignedShort:
221   case UnsignedInt:
222   case UnsignedLong:
223   case UnsignedLongLong:
224     return false;
225   };
226 }
227 
228 /// setForcedLangOptions - Set forced language options.
229 /// Apply changes to the target information with respect to certain
230 /// language options which change the target configuration.
231 void TargetInfo::setForcedLangOptions(LangOptions &Opts) {
232   if (Opts.NoBitFieldTypeAlign)
233     UseBitFieldTypeAlignment = false;
234   if (Opts.ShortWChar)
235     WCharType = UnsignedShort;
236 
237   if (Opts.OpenCL) {
238     // OpenCL C requires specific widths for types, irrespective of
239     // what these normally are for the target.
240     // We also define long long and long double here, although the
241     // OpenCL standard only mentions these as "reserved".
242     IntWidth = IntAlign = 32;
243     LongWidth = LongAlign = 64;
244     LongLongWidth = LongLongAlign = 128;
245     HalfWidth = HalfAlign = 16;
246     FloatWidth = FloatAlign = 32;
247     DoubleWidth = DoubleAlign = 64;
248     LongDoubleWidth = LongDoubleAlign = 128;
249 
250     assert(PointerWidth == 32 || PointerWidth == 64);
251     bool is32BitArch = PointerWidth == 32;
252     SizeType = is32BitArch ? UnsignedInt : UnsignedLong;
253     PtrDiffType = is32BitArch ? SignedInt : SignedLong;
254     IntPtrType = is32BitArch ? SignedInt : SignedLong;
255 
256     IntMaxType = SignedLongLong;
257     UIntMaxType = UnsignedLongLong;
258     Int64Type = SignedLong;
259 
260     HalfFormat = &llvm::APFloat::IEEEhalf;
261     FloatFormat = &llvm::APFloat::IEEEsingle;
262     DoubleFormat = &llvm::APFloat::IEEEdouble;
263     LongDoubleFormat = &llvm::APFloat::IEEEquad;
264   }
265 }
266 
267 //===----------------------------------------------------------------------===//
268 
269 
270 static StringRef removeGCCRegisterPrefix(StringRef Name) {
271   if (Name[0] == '%' || Name[0] == '#')
272     Name = Name.substr(1);
273 
274   return Name;
275 }
276 
277 /// isValidClobber - Returns whether the passed in string is
278 /// a valid clobber in an inline asm statement. This is used by
279 /// Sema.
280 bool TargetInfo::isValidClobber(StringRef Name) const {
281   return (isValidGCCRegisterName(Name) ||
282 	  Name == "memory" || Name == "cc");
283 }
284 
285 /// isValidGCCRegisterName - Returns whether the passed in string
286 /// is a valid register name according to GCC. This is used by Sema for
287 /// inline asm statements.
288 bool TargetInfo::isValidGCCRegisterName(StringRef Name) const {
289   if (Name.empty())
290     return false;
291 
292   const char * const *Names;
293   unsigned NumNames;
294 
295   // Get rid of any register prefix.
296   Name = removeGCCRegisterPrefix(Name);
297 
298   getGCCRegNames(Names, NumNames);
299 
300   // If we have a number it maps to an entry in the register name array.
301   if (isDigit(Name[0])) {
302     int n;
303     if (!Name.getAsInteger(0, n))
304       return n >= 0 && (unsigned)n < NumNames;
305   }
306 
307   // Check register names.
308   for (unsigned i = 0; i < NumNames; i++) {
309     if (Name == Names[i])
310       return true;
311   }
312 
313   // Check any additional names that we have.
314   const AddlRegName *AddlNames;
315   unsigned NumAddlNames;
316   getGCCAddlRegNames(AddlNames, NumAddlNames);
317   for (unsigned i = 0; i < NumAddlNames; i++)
318     for (unsigned j = 0; j < llvm::array_lengthof(AddlNames[i].Names); j++) {
319       if (!AddlNames[i].Names[j])
320 	break;
321       // Make sure the register that the additional name is for is within
322       // the bounds of the register names from above.
323       if (AddlNames[i].Names[j] == Name && AddlNames[i].RegNum < NumNames)
324 	return true;
325   }
326 
327   // Now check aliases.
328   const GCCRegAlias *Aliases;
329   unsigned NumAliases;
330 
331   getGCCRegAliases(Aliases, NumAliases);
332   for (unsigned i = 0; i < NumAliases; i++) {
333     for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) {
334       if (!Aliases[i].Aliases[j])
335         break;
336       if (Aliases[i].Aliases[j] == Name)
337         return true;
338     }
339   }
340 
341   return false;
342 }
343 
344 StringRef
345 TargetInfo::getNormalizedGCCRegisterName(StringRef Name) const {
346   assert(isValidGCCRegisterName(Name) && "Invalid register passed in");
347 
348   // Get rid of any register prefix.
349   Name = removeGCCRegisterPrefix(Name);
350 
351   const char * const *Names;
352   unsigned NumNames;
353 
354   getGCCRegNames(Names, NumNames);
355 
356   // First, check if we have a number.
357   if (isDigit(Name[0])) {
358     int n;
359     if (!Name.getAsInteger(0, n)) {
360       assert(n >= 0 && (unsigned)n < NumNames &&
361              "Out of bounds register number!");
362       return Names[n];
363     }
364   }
365 
366   // Check any additional names that we have.
367   const AddlRegName *AddlNames;
368   unsigned NumAddlNames;
369   getGCCAddlRegNames(AddlNames, NumAddlNames);
370   for (unsigned i = 0; i < NumAddlNames; i++)
371     for (unsigned j = 0; j < llvm::array_lengthof(AddlNames[i].Names); j++) {
372       if (!AddlNames[i].Names[j])
373 	break;
374       // Make sure the register that the additional name is for is within
375       // the bounds of the register names from above.
376       if (AddlNames[i].Names[j] == Name && AddlNames[i].RegNum < NumNames)
377 	return Name;
378     }
379 
380   // Now check aliases.
381   const GCCRegAlias *Aliases;
382   unsigned NumAliases;
383 
384   getGCCRegAliases(Aliases, NumAliases);
385   for (unsigned i = 0; i < NumAliases; i++) {
386     for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) {
387       if (!Aliases[i].Aliases[j])
388         break;
389       if (Aliases[i].Aliases[j] == Name)
390         return Aliases[i].Register;
391     }
392   }
393 
394   return Name;
395 }
396 
397 bool TargetInfo::validateOutputConstraint(ConstraintInfo &Info) const {
398   const char *Name = Info.getConstraintStr().c_str();
399   // An output constraint must start with '=' or '+'
400   if (*Name != '=' && *Name != '+')
401     return false;
402 
403   if (*Name == '+')
404     Info.setIsReadWrite();
405 
406   Name++;
407   while (*Name) {
408     switch (*Name) {
409     default:
410       if (!validateAsmConstraint(Name, Info)) {
411         // FIXME: We temporarily return false
412         // so we can add more constraints as we hit it.
413         // Eventually, an unknown constraint should just be treated as 'g'.
414         return false;
415       }
416     case '&': // early clobber.
417       break;
418     case '%': // commutative.
419       // FIXME: Check that there is a another register after this one.
420       break;
421     case 'r': // general register.
422       Info.setAllowsRegister();
423       break;
424     case 'm': // memory operand.
425     case 'o': // offsetable memory operand.
426     case 'V': // non-offsetable memory operand.
427     case '<': // autodecrement memory operand.
428     case '>': // autoincrement memory operand.
429       Info.setAllowsMemory();
430       break;
431     case 'g': // general register, memory operand or immediate integer.
432     case 'X': // any operand.
433       Info.setAllowsRegister();
434       Info.setAllowsMemory();
435       break;
436     case ',': // multiple alternative constraint.  Pass it.
437       // Handle additional optional '=' or '+' modifiers.
438       if (Name[1] == '=' || Name[1] == '+')
439         Name++;
440       break;
441     case '?': // Disparage slightly code.
442     case '!': // Disparage severely.
443     case '#': // Ignore as constraint.
444     case '*': // Ignore for choosing register preferences.
445       break;  // Pass them.
446     }
447 
448     Name++;
449   }
450 
451   // If a constraint allows neither memory nor register operands it contains
452   // only modifiers. Reject it.
453   return Info.allowsMemory() || Info.allowsRegister();
454 }
455 
456 bool TargetInfo::resolveSymbolicName(const char *&Name,
457                                      ConstraintInfo *OutputConstraints,
458                                      unsigned NumOutputs,
459                                      unsigned &Index) const {
460   assert(*Name == '[' && "Symbolic name did not start with '['");
461   Name++;
462   const char *Start = Name;
463   while (*Name && *Name != ']')
464     Name++;
465 
466   if (!*Name) {
467     // Missing ']'
468     return false;
469   }
470 
471   std::string SymbolicName(Start, Name - Start);
472 
473   for (Index = 0; Index != NumOutputs; ++Index)
474     if (SymbolicName == OutputConstraints[Index].getName())
475       return true;
476 
477   return false;
478 }
479 
480 bool TargetInfo::validateInputConstraint(ConstraintInfo *OutputConstraints,
481                                          unsigned NumOutputs,
482                                          ConstraintInfo &Info) const {
483   const char *Name = Info.ConstraintStr.c_str();
484 
485   while (*Name) {
486     switch (*Name) {
487     default:
488       // Check if we have a matching constraint
489       if (*Name >= '0' && *Name <= '9') {
490         unsigned i = *Name - '0';
491 
492         // Check if matching constraint is out of bounds.
493         if (i >= NumOutputs)
494           return false;
495 
496         // A number must refer to an output only operand.
497         if (OutputConstraints[i].isReadWrite())
498           return false;
499 
500         // If the constraint is already tied, it must be tied to the
501         // same operand referenced to by the number.
502         if (Info.hasTiedOperand() && Info.getTiedOperand() != i)
503           return false;
504 
505         // The constraint should have the same info as the respective
506         // output constraint.
507         Info.setTiedOperand(i, OutputConstraints[i]);
508       } else if (!validateAsmConstraint(Name, Info)) {
509         // FIXME: This error return is in place temporarily so we can
510         // add more constraints as we hit it.  Eventually, an unknown
511         // constraint should just be treated as 'g'.
512         return false;
513       }
514       break;
515     case '[': {
516       unsigned Index = 0;
517       if (!resolveSymbolicName(Name, OutputConstraints, NumOutputs, Index))
518         return false;
519 
520       // If the constraint is already tied, it must be tied to the
521       // same operand referenced to by the number.
522       if (Info.hasTiedOperand() && Info.getTiedOperand() != Index)
523         return false;
524 
525       Info.setTiedOperand(Index, OutputConstraints[Index]);
526       break;
527     }
528     case '%': // commutative
529       // FIXME: Fail if % is used with the last operand.
530       break;
531     case 'i': // immediate integer.
532     case 'n': // immediate integer with a known value.
533       break;
534     case 'I':  // Various constant constraints with target-specific meanings.
535     case 'J':
536     case 'K':
537     case 'L':
538     case 'M':
539     case 'N':
540     case 'O':
541     case 'P':
542       break;
543     case 'r': // general register.
544       Info.setAllowsRegister();
545       break;
546     case 'm': // memory operand.
547     case 'o': // offsettable memory operand.
548     case 'V': // non-offsettable memory operand.
549     case '<': // autodecrement memory operand.
550     case '>': // autoincrement memory operand.
551       Info.setAllowsMemory();
552       break;
553     case 'g': // general register, memory operand or immediate integer.
554     case 'X': // any operand.
555       Info.setAllowsRegister();
556       Info.setAllowsMemory();
557       break;
558     case 'E': // immediate floating point.
559     case 'F': // immediate floating point.
560     case 'p': // address operand.
561       break;
562     case ',': // multiple alternative constraint.  Ignore comma.
563       break;
564     case '?': // Disparage slightly code.
565     case '!': // Disparage severely.
566     case '#': // Ignore as constraint.
567     case '*': // Ignore for choosing register preferences.
568       break;  // Pass them.
569     }
570 
571     Name++;
572   }
573 
574   return true;
575 }
576 
577 bool TargetCXXABI::tryParse(llvm::StringRef name) {
578   const Kind unknown = static_cast<Kind>(-1);
579   Kind kind = llvm::StringSwitch<Kind>(name)
580     .Case("arm", GenericARM)
581     .Case("ios", iOS)
582     .Case("itanium", GenericItanium)
583     .Case("microsoft", Microsoft)
584     .Default(unknown);
585   if (kind == unknown) return false;
586 
587   set(kind);
588   return true;
589 }
590