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