clang  19.0.0git
X86.cpp
Go to the documentation of this file.
1 //===- X86.cpp ------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ABIInfoImpl.h"
10 #include "TargetInfo.h"
12 #include "llvm/ADT/SmallBitVector.h"
13 
14 using namespace clang;
15 using namespace clang::CodeGen;
16 
17 namespace {
18 
19 /// IsX86_MMXType - Return true if this is an MMX type.
20 bool IsX86_MMXType(llvm::Type *IRType) {
21  // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
22  return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
23  cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
24  IRType->getScalarSizeInBits() != 64;
25 }
26 
27 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
28  StringRef Constraint,
29  llvm::Type* Ty) {
30  bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
31  .Cases("y", "&y", "^Ym", true)
32  .Default(false);
33  if (IsMMXCons && Ty->isVectorTy()) {
34  if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedValue() !=
35  64) {
36  // Invalid MMX constraint
37  return nullptr;
38  }
39 
40  return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
41  }
42 
43  if (Constraint == "k") {
44  llvm::Type *Int1Ty = llvm::Type::getInt1Ty(CGF.getLLVMContext());
45  return llvm::FixedVectorType::get(Int1Ty, Ty->getScalarSizeInBits());
46  }
47 
48  // No operation needed
49  return Ty;
50 }
51 
52 /// Returns true if this type can be passed in SSE registers with the
53 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
54 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
55  if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
56  if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
57  if (BT->getKind() == BuiltinType::LongDouble) {
58  if (&Context.getTargetInfo().getLongDoubleFormat() ==
59  &llvm::APFloat::x87DoubleExtended())
60  return false;
61  }
62  return true;
63  }
64  } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
65  // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
66  // registers specially.
67  unsigned VecSize = Context.getTypeSize(VT);
68  if (VecSize == 128 || VecSize == 256 || VecSize == 512)
69  return true;
70  }
71  return false;
72 }
73 
74 /// Returns true if this aggregate is small enough to be passed in SSE registers
75 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
76 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
77  return NumMembers <= 4;
78 }
79 
80 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
81 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
82  auto AI = ABIArgInfo::getDirect(T);
83  AI.setInReg(true);
84  AI.setCanBeFlattened(false);
85  return AI;
86 }
87 
88 //===----------------------------------------------------------------------===//
89 // X86-32 ABI Implementation
90 //===----------------------------------------------------------------------===//
91 
92 /// Similar to llvm::CCState, but for Clang.
93 struct CCState {
94  CCState(CGFunctionInfo &FI)
95  : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()),
96  Required(FI.getRequiredArgs()), IsDelegateCall(FI.isDelegateCall()) {}
97 
98  llvm::SmallBitVector IsPreassigned;
99  unsigned CC = CallingConv::CC_C;
100  unsigned FreeRegs = 0;
101  unsigned FreeSSERegs = 0;
103  bool IsDelegateCall = false;
104 };
105 
106 /// X86_32ABIInfo - The X86-32 ABI information.
107 class X86_32ABIInfo : public ABIInfo {
108  enum Class {
109  Integer,
110  Float
111  };
112 
113  static const unsigned MinABIStackAlignInBytes = 4;
114 
115  bool IsDarwinVectorABI;
116  bool IsRetSmallStructInRegABI;
117  bool IsWin32StructABI;
118  bool IsSoftFloatABI;
119  bool IsMCUABI;
120  bool IsLinuxABI;
121  unsigned DefaultNumRegisterParameters;
122 
123  static bool isRegisterSize(unsigned Size) {
124  return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
125  }
126 
127  bool isHomogeneousAggregateBaseType(QualType Ty) const override {
128  // FIXME: Assumes vectorcall is in use.
129  return isX86VectorTypeForVectorCall(getContext(), Ty);
130  }
131 
132  bool isHomogeneousAggregateSmallEnough(const Type *Ty,
133  uint64_t NumMembers) const override {
134  // FIXME: Assumes vectorcall is in use.
135  return isX86VectorCallAggregateSmallEnough(NumMembers);
136  }
137 
138  bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
139 
140  /// getIndirectResult - Give a source type \arg Ty, return a suitable result
141  /// such that the argument will be passed in memory.
142  ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
143 
144  ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
145 
146  /// Return the alignment to use for the given type on the stack.
147  unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
148 
149  Class classify(QualType Ty) const;
150  ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
152  unsigned ArgIndex) const;
153 
154  /// Updates the number of available free registers, returns
155  /// true if any registers were allocated.
156  bool updateFreeRegs(QualType Ty, CCState &State) const;
157 
158  bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
159  bool &NeedsPadding) const;
160  bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
161 
162  bool canExpandIndirectArgument(QualType Ty) const;
163 
164  /// Rewrite the function info so that all memory arguments use
165  /// inalloca.
166  void rewriteWithInAlloca(CGFunctionInfo &FI) const;
167 
168  void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
169  CharUnits &StackOffset, ABIArgInfo &Info,
170  QualType Type) const;
171  void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
172 
173 public:
174 
175  void computeInfo(CGFunctionInfo &FI) const override;
176  Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
177  QualType Ty) const override;
178 
179  X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
180  bool RetSmallStructInRegABI, bool Win32StructABI,
181  unsigned NumRegisterParameters, bool SoftFloatABI)
182  : ABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
183  IsRetSmallStructInRegABI(RetSmallStructInRegABI),
184  IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
185  IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
186  IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
187  CGT.getTarget().getTriple().isOSCygMing()),
188  DefaultNumRegisterParameters(NumRegisterParameters) {}
189 };
190 
191 class X86_32SwiftABIInfo : public SwiftABIInfo {
192 public:
193  explicit X86_32SwiftABIInfo(CodeGenTypes &CGT)
194  : SwiftABIInfo(CGT, /*SwiftErrorInRegister=*/false) {}
195 
197  bool AsReturnValue) const override {
198  // LLVM's x86-32 lowering currently only assigns up to three
199  // integer registers and three fp registers. Oddly, it'll use up to
200  // four vector registers for vectors, but those can overlap with the
201  // scalar registers.
202  return occupiesMoreThan(ComponentTys, /*total=*/3);
203  }
204 };
205 
206 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
207 public:
208  X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
209  bool RetSmallStructInRegABI, bool Win32StructABI,
210  unsigned NumRegisterParameters, bool SoftFloatABI)
211  : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
212  CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
213  NumRegisterParameters, SoftFloatABI)) {
214  SwiftInfo = std::make_unique<X86_32SwiftABIInfo>(CGT);
215  }
216 
217  static bool isStructReturnInRegABI(
218  const llvm::Triple &Triple, const CodeGenOptions &Opts);
219 
220  void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
221  CodeGen::CodeGenModule &CGM) const override;
222 
223  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
224  // Darwin uses different dwarf register numbers for EH.
225  if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
226  return 4;
227  }
228 
229  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
230  llvm::Value *Address) const override;
231 
232  llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
233  StringRef Constraint,
234  llvm::Type* Ty) const override {
235  return X86AdjustInlineAsmType(CGF, Constraint, Ty);
236  }
237 
238  void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
239  std::string &Constraints,
240  std::vector<llvm::Type *> &ResultRegTypes,
241  std::vector<llvm::Type *> &ResultTruncRegTypes,
242  std::vector<LValue> &ResultRegDests,
243  std::string &AsmString,
244  unsigned NumOutputs) const override;
245 
246  StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
247  return "movl\t%ebp, %ebp"
248  "\t\t// marker for objc_retainAutoreleaseReturnValue";
249  }
250 };
251 
252 }
253 
254 /// Rewrite input constraint references after adding some output constraints.
255 /// In the case where there is one output and one input and we add one output,
256 /// we need to replace all operand references greater than or equal to 1:
257 /// mov $0, $1
258 /// mov eax, $1
259 /// The result will be:
260 /// mov $0, $2
261 /// mov eax, $2
262 static void rewriteInputConstraintReferences(unsigned FirstIn,
263  unsigned NumNewOuts,
264  std::string &AsmString) {
265  std::string Buf;
266  llvm::raw_string_ostream OS(Buf);
267  size_t Pos = 0;
268  while (Pos < AsmString.size()) {
269  size_t DollarStart = AsmString.find('$', Pos);
270  if (DollarStart == std::string::npos)
271  DollarStart = AsmString.size();
272  size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
273  if (DollarEnd == std::string::npos)
274  DollarEnd = AsmString.size();
275  OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
276  Pos = DollarEnd;
277  size_t NumDollars = DollarEnd - DollarStart;
278  if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
279  // We have an operand reference.
280  size_t DigitStart = Pos;
281  if (AsmString[DigitStart] == '{') {
282  OS << '{';
283  ++DigitStart;
284  }
285  size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
286  if (DigitEnd == std::string::npos)
287  DigitEnd = AsmString.size();
288  StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
289  unsigned OperandIndex;
290  if (!OperandStr.getAsInteger(10, OperandIndex)) {
291  if (OperandIndex >= FirstIn)
292  OperandIndex += NumNewOuts;
293  OS << OperandIndex;
294  } else {
295  OS << OperandStr;
296  }
297  Pos = DigitEnd;
298  }
299  }
300  AsmString = std::move(OS.str());
301 }
302 
303 /// Add output constraints for EAX:EDX because they are return registers.
304 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
305  CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
306  std::vector<llvm::Type *> &ResultRegTypes,
307  std::vector<llvm::Type *> &ResultTruncRegTypes,
308  std::vector<LValue> &ResultRegDests, std::string &AsmString,
309  unsigned NumOutputs) const {
310  uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
311 
312  // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
313  // larger.
314  if (!Constraints.empty())
315  Constraints += ',';
316  if (RetWidth <= 32) {
317  Constraints += "={eax}";
318  ResultRegTypes.push_back(CGF.Int32Ty);
319  } else {
320  // Use the 'A' constraint for EAX:EDX.
321  Constraints += "=A";
322  ResultRegTypes.push_back(CGF.Int64Ty);
323  }
324 
325  // Truncate EAX or EAX:EDX to an integer of the appropriate size.
326  llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
327  ResultTruncRegTypes.push_back(CoerceTy);
328 
329  // Coerce the integer by bitcasting the return slot pointer.
330  ReturnSlot.setAddress(ReturnSlot.getAddress().withElementType(CoerceTy));
331  ResultRegDests.push_back(ReturnSlot);
332 
333  rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
334 }
335 
336 /// shouldReturnTypeInRegister - Determine if the given type should be
337 /// returned in a register (for the Darwin and MCU ABI).
338 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
339  ASTContext &Context) const {
340  uint64_t Size = Context.getTypeSize(Ty);
341 
342  // For i386, type must be register sized.
343  // For the MCU ABI, it only needs to be <= 8-byte
344  if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
345  return false;
346 
347  if (Ty->isVectorType()) {
348  // 64- and 128- bit vectors inside structures are not returned in
349  // registers.
350  if (Size == 64 || Size == 128)
351  return false;
352 
353  return true;
354  }
355 
356  // If this is a builtin, pointer, enum, complex type, member pointer, or
357  // member function pointer it is ok.
358  if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
359  Ty->isAnyComplexType() || Ty->isEnumeralType() ||
361  return true;
362 
363  // Arrays are treated like records.
364  if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
365  return shouldReturnTypeInRegister(AT->getElementType(), Context);
366 
367  // Otherwise, it must be a record type.
368  const RecordType *RT = Ty->getAs<RecordType>();
369  if (!RT) return false;
370 
371  // FIXME: Traverse bases here too.
372 
373  // Structure types are passed in register if all fields would be
374  // passed in a register.
375  for (const auto *FD : RT->getDecl()->fields()) {
376  // Empty fields are ignored.
377  if (isEmptyField(Context, FD, true))
378  continue;
379 
380  // Check fields recursively.
381  if (!shouldReturnTypeInRegister(FD->getType(), Context))
382  return false;
383  }
384  return true;
385 }
386 
387 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
388  // Treat complex types as the element type.
389  if (const ComplexType *CTy = Ty->getAs<ComplexType>())
390  Ty = CTy->getElementType();
391 
392  // Check for a type which we know has a simple scalar argument-passing
393  // convention without any padding. (We're specifically looking for 32
394  // and 64-bit integer and integer-equivalents, float, and double.)
395  if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
396  !Ty->isEnumeralType() && !Ty->isBlockPointerType())
397  return false;
398 
399  uint64_t Size = Context.getTypeSize(Ty);
400  return Size == 32 || Size == 64;
401 }
402 
403 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
404  uint64_t &Size) {
405  for (const auto *FD : RD->fields()) {
406  // Scalar arguments on the stack get 4 byte alignment on x86. If the
407  // argument is smaller than 32-bits, expanding the struct will create
408  // alignment padding.
409  if (!is32Or64BitBasicType(FD->getType(), Context))
410  return false;
411 
412  // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
413  // how to expand them yet, and the predicate for telling if a bitfield still
414  // counts as "basic" is more complicated than what we were doing previously.
415  if (FD->isBitField())
416  return false;
417 
418  Size += Context.getTypeSize(FD->getType());
419  }
420  return true;
421 }
422 
423 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
424  uint64_t &Size) {
425  // Don't do this if there are any non-empty bases.
426  for (const CXXBaseSpecifier &Base : RD->bases()) {
427  if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
428  Size))
429  return false;
430  }
431  if (!addFieldSizes(Context, RD, Size))
432  return false;
433  return true;
434 }
435 
436 /// Test whether an argument type which is to be passed indirectly (on the
437 /// stack) would have the equivalent layout if it was expanded into separate
438 /// arguments. If so, we prefer to do the latter to avoid inhibiting
439 /// optimizations.
440 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
441  // We can only expand structure types.
442  const RecordType *RT = Ty->getAs<RecordType>();
443  if (!RT)
444  return false;
445  const RecordDecl *RD = RT->getDecl();
446  uint64_t Size = 0;
447  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
448  if (!IsWin32StructABI) {
449  // On non-Windows, we have to conservatively match our old bitcode
450  // prototypes in order to be ABI-compatible at the bitcode level.
451  if (!CXXRD->isCLike())
452  return false;
453  } else {
454  // Don't do this for dynamic classes.
455  if (CXXRD->isDynamicClass())
456  return false;
457  }
458  if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
459  return false;
460  } else {
461  if (!addFieldSizes(getContext(), RD, Size))
462  return false;
463  }
464 
465  // We can do this if there was no alignment padding.
466  return Size == getContext().getTypeSize(Ty);
467 }
468 
469 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
470  // If the return value is indirect, then the hidden argument is consuming one
471  // integer register.
472  if (State.FreeRegs) {
473  --State.FreeRegs;
474  if (!IsMCUABI)
475  return getNaturalAlignIndirectInReg(RetTy);
476  }
477  return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
478 }
479 
481  CCState &State) const {
482  if (RetTy->isVoidType())
483  return ABIArgInfo::getIgnore();
484 
485  const Type *Base = nullptr;
486  uint64_t NumElts = 0;
487  if ((State.CC == llvm::CallingConv::X86_VectorCall ||
488  State.CC == llvm::CallingConv::X86_RegCall) &&
489  isHomogeneousAggregate(RetTy, Base, NumElts)) {
490  // The LLVM struct type for such an aggregate should lower properly.
491  return ABIArgInfo::getDirect();
492  }
493 
494  if (const VectorType *VT = RetTy->getAs<VectorType>()) {
495  // On Darwin, some vectors are returned in registers.
496  if (IsDarwinVectorABI) {
497  uint64_t Size = getContext().getTypeSize(RetTy);
498 
499  // 128-bit vectors are a special case; they are returned in
500  // registers and we need to make sure to pick a type the LLVM
501  // backend will like.
502  if (Size == 128)
503  return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
504  llvm::Type::getInt64Ty(getVMContext()), 2));
505 
506  // Always return in register if it fits in a general purpose
507  // register, or if it is 64 bits and has a single element.
508  if ((Size == 8 || Size == 16 || Size == 32) ||
509  (Size == 64 && VT->getNumElements() == 1))
510  return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
511  Size));
512 
513  return getIndirectReturnResult(RetTy, State);
514  }
515 
516  return ABIArgInfo::getDirect();
517  }
518 
519  if (isAggregateTypeForABI(RetTy)) {
520  if (const RecordType *RT = RetTy->getAs<RecordType>()) {
521  // Structures with flexible arrays are always indirect.
522  if (RT->getDecl()->hasFlexibleArrayMember())
523  return getIndirectReturnResult(RetTy, State);
524  }
525 
526  // If specified, structs and unions are always indirect.
527  if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
528  return getIndirectReturnResult(RetTy, State);
529 
530  // Ignore empty structs/unions.
531  if (isEmptyRecord(getContext(), RetTy, true))
532  return ABIArgInfo::getIgnore();
533 
534  // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
535  if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
536  QualType ET = getContext().getCanonicalType(CT->getElementType());
537  if (ET->isFloat16Type())
538  return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
539  llvm::Type::getHalfTy(getVMContext()), 2));
540  }
541 
542  // Small structures which are register sized are generally returned
543  // in a register.
544  if (shouldReturnTypeInRegister(RetTy, getContext())) {
545  uint64_t Size = getContext().getTypeSize(RetTy);
546 
547  // As a special-case, if the struct is a "single-element" struct, and
548  // the field is of type "float" or "double", return it in a
549  // floating-point register. (MSVC does not apply this special case.)
550  // We apply a similar transformation for pointer types to improve the
551  // quality of the generated IR.
552  if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
553  if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
554  || SeltTy->hasPointerRepresentation())
555  return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
556 
557  // FIXME: We should be able to narrow this integer in cases with dead
558  // padding.
559  return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
560  }
561 
562  return getIndirectReturnResult(RetTy, State);
563  }
564 
565  // Treat an enum type as its underlying type.
566  if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
567  RetTy = EnumTy->getDecl()->getIntegerType();
568 
569  if (const auto *EIT = RetTy->getAs<BitIntType>())
570  if (EIT->getNumBits() > 64)
571  return getIndirectReturnResult(RetTy, State);
572 
573  return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
575 }
576 
577 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
578  unsigned Align) const {
579  // Otherwise, if the alignment is less than or equal to the minimum ABI
580  // alignment, just use the default; the backend will handle this.
581  if (Align <= MinABIStackAlignInBytes)
582  return 0; // Use default alignment.
583 
584  if (IsLinuxABI) {
585  // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
586  // want to spend any effort dealing with the ramifications of ABI breaks.
587  //
588  // If the vector type is __m128/__m256/__m512, return the default alignment.
589  if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
590  return Align;
591  }
592  // On non-Darwin, the stack type alignment is always 4.
593  if (!IsDarwinVectorABI) {
594  // Set explicit alignment, since we may need to realign the top.
595  return MinABIStackAlignInBytes;
596  }
597 
598  // Otherwise, if the type contains an SSE vector type, the alignment is 16.
599  if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
600  isRecordWithSIMDVectorType(getContext(), Ty)))
601  return 16;
602 
603  return MinABIStackAlignInBytes;
604 }
605 
606 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
607  CCState &State) const {
608  if (!ByVal) {
609  if (State.FreeRegs) {
610  --State.FreeRegs; // Non-byval indirects just use one pointer.
611  if (!IsMCUABI)
612  return getNaturalAlignIndirectInReg(Ty);
613  }
614  return getNaturalAlignIndirect(Ty, false);
615  }
616 
617  // Compute the byval alignment.
618  unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
619  unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
620  if (StackAlign == 0)
621  return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
622 
623  // If the stack alignment is less than the type alignment, realign the
624  // argument.
625  bool Realign = TypeAlign > StackAlign;
627  /*ByVal=*/true, Realign);
628 }
629 
630 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
631  const Type *T = isSingleElementStruct(Ty, getContext());
632  if (!T)
633  T = Ty.getTypePtr();
634 
635  if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
636  BuiltinType::Kind K = BT->getKind();
637  if (K == BuiltinType::Float || K == BuiltinType::Double)
638  return Float;
639  }
640  return Integer;
641 }
642 
643 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
644  if (!IsSoftFloatABI) {
645  Class C = classify(Ty);
646  if (C == Float)
647  return false;
648  }
649 
650  unsigned Size = getContext().getTypeSize(Ty);
651  unsigned SizeInRegs = (Size + 31) / 32;
652 
653  if (SizeInRegs == 0)
654  return false;
655 
656  if (!IsMCUABI) {
657  if (SizeInRegs > State.FreeRegs) {
658  State.FreeRegs = 0;
659  return false;
660  }
661  } else {
662  // The MCU psABI allows passing parameters in-reg even if there are
663  // earlier parameters that are passed on the stack. Also,
664  // it does not allow passing >8-byte structs in-register,
665  // even if there are 3 free registers available.
666  if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
667  return false;
668  }
669 
670  State.FreeRegs -= SizeInRegs;
671  return true;
672 }
673 
674 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
675  bool &InReg,
676  bool &NeedsPadding) const {
677  // On Windows, aggregates other than HFAs are never passed in registers, and
678  // they do not consume register slots. Homogenous floating-point aggregates
679  // (HFAs) have already been dealt with at this point.
680  if (IsWin32StructABI && isAggregateTypeForABI(Ty))
681  return false;
682 
683  NeedsPadding = false;
684  InReg = !IsMCUABI;
685 
686  if (!updateFreeRegs(Ty, State))
687  return false;
688 
689  if (IsMCUABI)
690  return true;
691 
692  if (State.CC == llvm::CallingConv::X86_FastCall ||
693  State.CC == llvm::CallingConv::X86_VectorCall ||
694  State.CC == llvm::CallingConv::X86_RegCall) {
695  if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
696  NeedsPadding = true;
697 
698  return false;
699  }
700 
701  return true;
702 }
703 
704 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
705  bool IsPtrOrInt = (getContext().getTypeSize(Ty) <= 32) &&
706  (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
707  Ty->isReferenceType());
708 
709  if (!IsPtrOrInt && (State.CC == llvm::CallingConv::X86_FastCall ||
710  State.CC == llvm::CallingConv::X86_VectorCall))
711  return false;
712 
713  if (!updateFreeRegs(Ty, State))
714  return false;
715 
716  if (!IsPtrOrInt && State.CC == llvm::CallingConv::X86_RegCall)
717  return false;
718 
719  // Return true to apply inreg to all legal parameters except for MCU targets.
720  return !IsMCUABI;
721 }
722 
723 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
724  // Vectorcall x86 works subtly different than in x64, so the format is
725  // a bit different than the x64 version. First, all vector types (not HVAs)
726  // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
727  // This differs from the x64 implementation, where the first 6 by INDEX get
728  // registers.
729  // In the second pass over the arguments, HVAs are passed in the remaining
730  // vector registers if possible, or indirectly by address. The address will be
731  // passed in ECX/EDX if available. Any other arguments are passed according to
732  // the usual fastcall rules.
734  for (int I = 0, E = Args.size(); I < E; ++I) {
735  const Type *Base = nullptr;
736  uint64_t NumElts = 0;
737  const QualType &Ty = Args[I].type;
738  if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
739  isHomogeneousAggregate(Ty, Base, NumElts)) {
740  if (State.FreeSSERegs >= NumElts) {
741  State.FreeSSERegs -= NumElts;
742  Args[I].info = ABIArgInfo::getDirectInReg();
743  State.IsPreassigned.set(I);
744  }
745  }
746  }
747 }
748 
750  unsigned ArgIndex) const {
751  // FIXME: Set alignment on indirect arguments.
752  bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
753  bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
754  bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
755 
757  TypeInfo TI = getContext().getTypeInfo(Ty);
758 
759  // Check with the C++ ABI first.
760  const RecordType *RT = Ty->getAs<RecordType>();
761  if (RT) {
762  CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
763  if (RAA == CGCXXABI::RAA_Indirect) {
764  return getIndirectResult(Ty, false, State);
765  } else if (State.IsDelegateCall) {
766  // Avoid having different alignments on delegate call args by always
767  // setting the alignment to 4, which is what we do for inallocas.
768  ABIArgInfo Res = getIndirectResult(Ty, false, State);
770  return Res;
771  } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
772  // The field index doesn't matter, we'll fix it up later.
773  return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
774  }
775  }
776 
777  // Regcall uses the concept of a homogenous vector aggregate, similar
778  // to other targets.
779  const Type *Base = nullptr;
780  uint64_t NumElts = 0;
781  if ((IsRegCall || IsVectorCall) &&
782  isHomogeneousAggregate(Ty, Base, NumElts)) {
783  if (State.FreeSSERegs >= NumElts) {
784  State.FreeSSERegs -= NumElts;
785 
786  // Vectorcall passes HVAs directly and does not flatten them, but regcall
787  // does.
788  if (IsVectorCall)
789  return getDirectX86Hva();
790 
791  if (Ty->isBuiltinType() || Ty->isVectorType())
792  return ABIArgInfo::getDirect();
793  return ABIArgInfo::getExpand();
794  }
795  if (IsVectorCall && Ty->isBuiltinType())
796  return ABIArgInfo::getDirect();
797  return getIndirectResult(Ty, /*ByVal=*/false, State);
798  }
799 
800  if (isAggregateTypeForABI(Ty)) {
801  // Structures with flexible arrays are always indirect.
802  // FIXME: This should not be byval!
803  if (RT && RT->getDecl()->hasFlexibleArrayMember())
804  return getIndirectResult(Ty, true, State);
805 
806  // Ignore empty structs/unions on non-Windows.
807  if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
808  return ABIArgInfo::getIgnore();
809 
810  llvm::LLVMContext &LLVMContext = getVMContext();
811  llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
812  bool NeedsPadding = false;
813  bool InReg;
814  if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
815  unsigned SizeInRegs = (TI.Width + 31) / 32;
816  SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
817  llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
818  if (InReg)
819  return ABIArgInfo::getDirectInReg(Result);
820  else
821  return ABIArgInfo::getDirect(Result);
822  }
823  llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
824 
825  // Pass over-aligned aggregates to non-variadic functions on Windows
826  // indirectly. This behavior was added in MSVC 2015. Use the required
827  // alignment from the record layout, since that may be less than the
828  // regular type alignment, and types with required alignment of less than 4
829  // bytes are not passed indirectly.
830  if (IsWin32StructABI && State.Required.isRequiredArg(ArgIndex)) {
831  unsigned AlignInBits = 0;
832  if (RT) {
833  const ASTRecordLayout &Layout =
834  getContext().getASTRecordLayout(RT->getDecl());
835  AlignInBits = getContext().toBits(Layout.getRequiredAlignment());
836  } else if (TI.isAlignRequired()) {
837  AlignInBits = TI.Align;
838  }
839  if (AlignInBits > 32)
840  return getIndirectResult(Ty, /*ByVal=*/false, State);
841  }
842 
843  // Expand small (<= 128-bit) record types when we know that the stack layout
844  // of those arguments will match the struct. This is important because the
845  // LLVM backend isn't smart enough to remove byval, which inhibits many
846  // optimizations.
847  // Don't do this for the MCU if there are still free integer registers
848  // (see X86_64 ABI for full explanation).
849  if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
850  canExpandIndirectArgument(Ty))
852  IsFastCall || IsVectorCall || IsRegCall, PaddingType);
853 
854  return getIndirectResult(Ty, true, State);
855  }
856 
857  if (const VectorType *VT = Ty->getAs<VectorType>()) {
858  // On Windows, vectors are passed directly if registers are available, or
859  // indirectly if not. This avoids the need to align argument memory. Pass
860  // user-defined vector types larger than 512 bits indirectly for simplicity.
861  if (IsWin32StructABI) {
862  if (TI.Width <= 512 && State.FreeSSERegs > 0) {
863  --State.FreeSSERegs;
865  }
866  return getIndirectResult(Ty, /*ByVal=*/false, State);
867  }
868 
869  // On Darwin, some vectors are passed in memory, we handle this by passing
870  // it as an i8/i16/i32/i64.
871  if (IsDarwinVectorABI) {
872  if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
873  (TI.Width == 64 && VT->getNumElements() == 1))
874  return ABIArgInfo::getDirect(
875  llvm::IntegerType::get(getVMContext(), TI.Width));
876  }
877 
878  if (IsX86_MMXType(CGT.ConvertType(Ty)))
879  return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
880 
881  return ABIArgInfo::getDirect();
882  }
883 
884 
885  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
886  Ty = EnumTy->getDecl()->getIntegerType();
887 
888  bool InReg = shouldPrimitiveUseInReg(Ty, State);
889 
890  if (isPromotableIntegerTypeForABI(Ty)) {
891  if (InReg)
892  return ABIArgInfo::getExtendInReg(Ty);
893  return ABIArgInfo::getExtend(Ty);
894  }
895 
896  if (const auto *EIT = Ty->getAs<BitIntType>()) {
897  if (EIT->getNumBits() <= 64) {
898  if (InReg)
900  return ABIArgInfo::getDirect();
901  }
902  return getIndirectResult(Ty, /*ByVal=*/false, State);
903  }
904 
905  if (InReg)
907  return ABIArgInfo::getDirect();
908 }
909 
911  if (Ty->isVoidType())
912  return ABIArgInfo::getIgnore();
913 
914  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
915  Ty = EnumTy->getDecl()->getIntegerType();
916 
917  if (const RecordType *RT = Ty->getAs<RecordType>())
918  return ABIArgInfo::getIndirect(Context.getTypeAlignInChars(RT),
919  /*ByVal=*/false);
920 
921  if (Context.isPromotableIntegerType(Ty))
922  return ABIArgInfo::getExtend(Ty);
923 
924  return ABIArgInfo::getDirect();
925 }
926 
928  if (!Context.getLangOpts().OpenCL)
929  return false;
930  if (!Context.getLangOpts().OpenCLForceVectorABI)
931  return false;
932 
933  // Use OpenCL classify to prevent coercing.
934  // Vector ABI must be enforced by enabling the corresponding option.
935  // Otherwise, vector types will be coerced to a matching integer
936  // type to conform with ABI, e.g.: <8 x i8> will be coerced to i64.
937  FI.getReturnInfo() = classifyOpenCL(FI.getReturnType(), Context);
938 
939  for (auto &Arg : FI.arguments())
940  Arg.info = classifyOpenCL(Arg.type, Context);
941 
942  return true;
943 }
944 
945 
946 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
947  ASTContext &Context = getContext();
948  if (doOpenCLClassification(FI, Context))
949  return;
950 
951  CCState State(FI);
952  if (IsMCUABI)
953  State.FreeRegs = 3;
954  else if (State.CC == llvm::CallingConv::X86_FastCall) {
955  State.FreeRegs = 2;
956  State.FreeSSERegs = 3;
957  } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
958  State.FreeRegs = 2;
959  State.FreeSSERegs = 6;
960  } else if (FI.getHasRegParm())
961  State.FreeRegs = FI.getRegParm();
962  else if (State.CC == llvm::CallingConv::X86_RegCall) {
963  State.FreeRegs = 5;
964  State.FreeSSERegs = 8;
965  } else if (IsWin32StructABI) {
966  // Since MSVC 2015, the first three SSE vectors have been passed in
967  // registers. The rest are passed indirectly.
968  State.FreeRegs = DefaultNumRegisterParameters;
969  State.FreeSSERegs = 3;
970  } else
971  State.FreeRegs = DefaultNumRegisterParameters;
972 
973  if (!::classifyReturnType(getCXXABI(), FI, *this)) {
975  } else if (FI.getReturnInfo().isIndirect()) {
976  // The C++ ABI is not aware of register usage, so we have to check if the
977  // return value was sret and put it in a register ourselves if appropriate.
978  if (State.FreeRegs) {
979  --State.FreeRegs; // The sret parameter consumes a register.
980  if (!IsMCUABI)
981  FI.getReturnInfo().setInReg(true);
982  }
983  }
984 
985  // The chain argument effectively gives us another free register.
986  if (FI.isChainCall())
987  ++State.FreeRegs;
988 
989  // For vectorcall, do a first pass over the arguments, assigning FP and vector
990  // arguments to XMM registers as available.
991  if (State.CC == llvm::CallingConv::X86_VectorCall)
992  runVectorCallFirstPass(FI, State);
993 
994  bool UsedInAlloca = false;
996  for (unsigned I = 0, E = Args.size(); I < E; ++I) {
997  // Skip arguments that have already been assigned.
998  if (State.IsPreassigned.test(I))
999  continue;
1000 
1001  Args[I].info =
1002  classifyArgumentType(Args[I].type, State, I);
1003  UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1004  }
1005 
1006  // If we needed to use inalloca for any argument, do a second pass and rewrite
1007  // all the memory arguments to use inalloca.
1008  if (UsedInAlloca)
1009  rewriteWithInAlloca(FI);
1010 }
1011 
1012 void
1013 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1014  CharUnits &StackOffset, ABIArgInfo &Info,
1015  QualType Type) const {
1016  // Arguments are always 4-byte-aligned.
1017  CharUnits WordSize = CharUnits::fromQuantity(4);
1018  assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
1019 
1020  // sret pointers and indirect things will require an extra pointer
1021  // indirection, unless they are byval. Most things are byval, and will not
1022  // require this indirection.
1023  bool IsIndirect = false;
1024  if (Info.isIndirect() && !Info.getIndirectByVal())
1025  IsIndirect = true;
1026  Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
1027  llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
1028  if (IsIndirect)
1029  LLTy = llvm::PointerType::getUnqual(getVMContext());
1030  FrameFields.push_back(LLTy);
1031  StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
1032 
1033  // Insert padding bytes to respect alignment.
1034  CharUnits FieldEnd = StackOffset;
1035  StackOffset = FieldEnd.alignTo(WordSize);
1036  if (StackOffset != FieldEnd) {
1037  CharUnits NumBytes = StackOffset - FieldEnd;
1038  llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1039  Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1040  FrameFields.push_back(Ty);
1041  }
1042 }
1043 
1044 static bool isArgInAlloca(const ABIArgInfo &Info) {
1045  // Leave ignored and inreg arguments alone.
1046  switch (Info.getKind()) {
1047  case ABIArgInfo::InAlloca:
1048  return true;
1049  case ABIArgInfo::Ignore:
1051  return false;
1052  case ABIArgInfo::Indirect:
1053  case ABIArgInfo::Direct:
1054  case ABIArgInfo::Extend:
1055  return !Info.getInReg();
1056  case ABIArgInfo::Expand:
1058  // These are aggregate types which are never passed in registers when
1059  // inalloca is involved.
1060  return true;
1061  }
1062  llvm_unreachable("invalid enum");
1063 }
1064 
1065 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1066  assert(IsWin32StructABI && "inalloca only supported on win32");
1067 
1068  // Build a packed struct type for all of the arguments in memory.
1069  SmallVector<llvm::Type *, 6> FrameFields;
1070 
1071  // The stack alignment is always 4.
1072  CharUnits StackAlign = CharUnits::fromQuantity(4);
1073 
1074  CharUnits StackOffset;
1075  CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1076 
1077  // Put 'this' into the struct before 'sret', if necessary.
1078  bool IsThisCall =
1079  FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1080  ABIArgInfo &Ret = FI.getReturnInfo();
1081  if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1082  isArgInAlloca(I->info)) {
1083  addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1084  ++I;
1085  }
1086 
1087  // Put the sret parameter into the inalloca struct if it's in memory.
1088  if (Ret.isIndirect() && !Ret.getInReg()) {
1089  addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
1090  // On Windows, the hidden sret parameter is always returned in eax.
1091  Ret.setInAllocaSRet(IsWin32StructABI);
1092  }
1093 
1094  // Skip the 'this' parameter in ecx.
1095  if (IsThisCall)
1096  ++I;
1097 
1098  // Put arguments passed in memory into the struct.
1099  for (; I != E; ++I) {
1100  if (isArgInAlloca(I->info))
1101  addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1102  }
1103 
1104  FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1105  /*isPacked=*/true),
1106  StackAlign);
1107 }
1108 
1109 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1110  Address VAListAddr, QualType Ty) const {
1111 
1112  auto TypeInfo = getContext().getTypeInfoInChars(Ty);
1113 
1114  CCState State(*const_cast<CGFunctionInfo *>(CGF.CurFnInfo));
1115  ABIArgInfo AI = classifyArgumentType(Ty, State, /*ArgIndex*/ 0);
1116  // Empty records are ignored for parameter passing purposes.
1117  if (AI.isIgnore())
1118  return CGF.CreateMemTemp(Ty);
1119 
1120  // x86-32 changes the alignment of certain arguments on the stack.
1121  //
1122  // Just messing with TypeInfo like this works because we never pass
1123  // anything indirectly.
1125  getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
1126 
1127  return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1129  /*AllowHigherAlign*/ true);
1130 }
1131 
1132 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1133  const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1134  assert(Triple.getArch() == llvm::Triple::x86);
1135 
1136  switch (Opts.getStructReturnConvention()) {
1138  break;
1139  case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1140  return false;
1141  case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1142  return true;
1143  }
1144 
1145  if (Triple.isOSDarwin() || Triple.isOSIAMCU())
1146  return true;
1147 
1148  switch (Triple.getOS()) {
1149  case llvm::Triple::DragonFly:
1150  case llvm::Triple::FreeBSD:
1151  case llvm::Triple::OpenBSD:
1152  case llvm::Triple::Win32:
1153  return true;
1154  default:
1155  return false;
1156  }
1157 }
1158 
1159 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
1160  CodeGen::CodeGenModule &CGM) {
1161  if (!FD->hasAttr<AnyX86InterruptAttr>())
1162  return;
1163 
1164  llvm::Function *Fn = cast<llvm::Function>(GV);
1165  Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1166  if (FD->getNumParams() == 0)
1167  return;
1168 
1169  auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
1170  llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
1171  llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
1172  Fn->getContext(), ByValTy);
1173  Fn->addParamAttr(0, NewAttr);
1174 }
1175 
1176 void X86_32TargetCodeGenInfo::setTargetAttributes(
1177  const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1178  if (GV->isDeclaration())
1179  return;
1180  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1181  if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1182  llvm::Function *Fn = cast<llvm::Function>(GV);
1183  Fn->addFnAttr("stackrealign");
1184  }
1185 
1186  addX86InterruptAttrs(FD, GV, CGM);
1187  }
1188 }
1189 
1190 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1192  llvm::Value *Address) const {
1193  CodeGen::CGBuilderTy &Builder = CGF.Builder;
1194 
1195  llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
1196 
1197  // 0-7 are the eight integer registers; the order is different
1198  // on Darwin (for EH), but the range is the same.
1199  // 8 is %eip.
1200  AssignToArrayRange(Builder, Address, Four8, 0, 8);
1201 
1202  if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
1203  // 12-16 are st(0..4). Not sure why we stop at 4.
1204  // These have size 16, which is sizeof(long double) on
1205  // platforms with 8-byte alignment for that type.
1206  llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
1207  AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
1208 
1209  } else {
1210  // 9 is %eflags, which doesn't get a size on Darwin for some
1211  // reason.
1212  Builder.CreateAlignedStore(
1213  Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1214  CharUnits::One());
1215 
1216  // 11-16 are st(0..5). Not sure why we stop at 5.
1217  // These have size 12, which is sizeof(long double) on
1218  // platforms with 4-byte alignment for that type.
1219  llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
1220  AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1221  }
1222 
1223  return false;
1224 }
1225 
1226 //===----------------------------------------------------------------------===//
1227 // X86-64 ABI Implementation
1228 //===----------------------------------------------------------------------===//
1229 
1230 
1231 namespace {
1232 
1233 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1234 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1235  switch (AVXLevel) {
1237  return 512;
1238  case X86AVXABILevel::AVX:
1239  return 256;
1240  case X86AVXABILevel::None:
1241  return 128;
1242  }
1243  llvm_unreachable("Unknown AVXLevel");
1244 }
1245 
1246 /// X86_64ABIInfo - The X86_64 ABI information.
1247 class X86_64ABIInfo : public ABIInfo {
1248  enum Class {
1249  Integer = 0,
1250  SSE,
1251  SSEUp,
1252  X87,
1253  X87Up,
1254  ComplexX87,
1255  NoClass,
1256  Memory
1257  };
1258 
1259  /// merge - Implement the X86_64 ABI merging algorithm.
1260  ///
1261  /// Merge an accumulating classification \arg Accum with a field
1262  /// classification \arg Field.
1263  ///
1264  /// \param Accum - The accumulating classification. This should
1265  /// always be either NoClass or the result of a previous merge
1266  /// call. In addition, this should never be Memory (the caller
1267  /// should just return Memory for the aggregate).
1268  static Class merge(Class Accum, Class Field);
1269 
1270  /// postMerge - Implement the X86_64 ABI post merging algorithm.
1271  ///
1272  /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1273  /// final MEMORY or SSE classes when necessary.
1274  ///
1275  /// \param AggregateSize - The size of the current aggregate in
1276  /// the classification process.
1277  ///
1278  /// \param Lo - The classification for the parts of the type
1279  /// residing in the low word of the containing object.
1280  ///
1281  /// \param Hi - The classification for the parts of the type
1282  /// residing in the higher words of the containing object.
1283  ///
1284  void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1285 
1286  /// classify - Determine the x86_64 register classes in which the
1287  /// given type T should be passed.
1288  ///
1289  /// \param Lo - The classification for the parts of the type
1290  /// residing in the low word of the containing object.
1291  ///
1292  /// \param Hi - The classification for the parts of the type
1293  /// residing in the high word of the containing object.
1294  ///
1295  /// \param OffsetBase - The bit offset of this type in the
1296  /// containing object. Some parameters are classified different
1297  /// depending on whether they straddle an eightbyte boundary.
1298  ///
1299  /// \param isNamedArg - Whether the argument in question is a "named"
1300  /// argument, as used in AMD64-ABI 3.5.7.
1301  ///
1302  /// \param IsRegCall - Whether the calling conversion is regcall.
1303  ///
1304  /// If a word is unused its result will be NoClass; if a type should
1305  /// be passed in Memory then at least the classification of \arg Lo
1306  /// will be Memory.
1307  ///
1308  /// The \arg Lo class will be NoClass iff the argument is ignored.
1309  ///
1310  /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1311  /// also be ComplexX87.
1312  void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1313  bool isNamedArg, bool IsRegCall = false) const;
1314 
1315  llvm::Type *GetByteVectorType(QualType Ty) const;
1316  llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1317  unsigned IROffset, QualType SourceTy,
1318  unsigned SourceOffset) const;
1319  llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1320  unsigned IROffset, QualType SourceTy,
1321  unsigned SourceOffset) const;
1322 
1323  /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1324  /// such that the argument will be returned in memory.
1325  ABIArgInfo getIndirectReturnResult(QualType Ty) const;
1326 
1327  /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1328  /// such that the argument will be passed in memory.
1329  ///
1330  /// \param freeIntRegs - The number of free integer registers remaining
1331  /// available.
1332  ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
1333 
1334  ABIArgInfo classifyReturnType(QualType RetTy) const;
1335 
1336  ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
1337  unsigned &neededInt, unsigned &neededSSE,
1338  bool isNamedArg,
1339  bool IsRegCall = false) const;
1340 
1341  ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
1342  unsigned &NeededSSE,
1343  unsigned &MaxVectorWidth) const;
1344 
1345  ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
1346  unsigned &NeededSSE,
1347  unsigned &MaxVectorWidth) const;
1348 
1349  bool IsIllegalVectorType(QualType Ty) const;
1350 
1351  /// The 0.98 ABI revision clarified a lot of ambiguities,
1352  /// unfortunately in ways that were not always consistent with
1353  /// certain previous compilers. In particular, platforms which
1354  /// required strict binary compatibility with older versions of GCC
1355  /// may need to exempt themselves.
1356  bool honorsRevision0_98() const {
1357  return !getTarget().getTriple().isOSDarwin();
1358  }
1359 
1360  /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
1361  /// classify it as INTEGER (for compatibility with older clang compilers).
1362  bool classifyIntegerMMXAsSSE() const {
1363  // Clang <= 3.8 did not do this.
1364  if (getContext().getLangOpts().getClangABICompat() <=
1366  return false;
1367 
1368  const llvm::Triple &Triple = getTarget().getTriple();
1369  if (Triple.isOSDarwin() || Triple.isPS() || Triple.isOSFreeBSD())
1370  return false;
1371  return true;
1372  }
1373 
1374  // GCC classifies vectors of __int128 as memory.
1375  bool passInt128VectorsInMem() const {
1376  // Clang <= 9.0 did not do this.
1377  if (getContext().getLangOpts().getClangABICompat() <=
1379  return false;
1380 
1381  const llvm::Triple &T = getTarget().getTriple();
1382  return T.isOSLinux() || T.isOSNetBSD();
1383  }
1384 
1385  X86AVXABILevel AVXLevel;
1386  // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1387  // 64-bit hardware.
1388  bool Has64BitPointers;
1389 
1390 public:
1391  X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1392  : ABIInfo(CGT), AVXLevel(AVXLevel),
1393  Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {}
1394 
1395  bool isPassedUsingAVXType(QualType type) const {
1396  unsigned neededInt, neededSSE;
1397  // The freeIntRegs argument doesn't matter here.
1398  ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1399  /*isNamedArg*/true);
1400  if (info.isDirect()) {
1401  llvm::Type *ty = info.getCoerceToType();
1402  if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1403  return vectorTy->getPrimitiveSizeInBits().getFixedValue() > 128;
1404  }
1405  return false;
1406  }
1407 
1408  void computeInfo(CGFunctionInfo &FI) const override;
1409 
1410  Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1411  QualType Ty) const override;
1412  Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1413  QualType Ty) const override;
1414 
1415  bool has64BitPointers() const {
1416  return Has64BitPointers;
1417  }
1418 };
1419 
1420 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
1421 class WinX86_64ABIInfo : public ABIInfo {
1422 public:
1423  WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1424  : ABIInfo(CGT), AVXLevel(AVXLevel),
1425  IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
1426 
1427  void computeInfo(CGFunctionInfo &FI) const override;
1428 
1429  Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1430  QualType Ty) const override;
1431 
1432  bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1433  // FIXME: Assumes vectorcall is in use.
1434  return isX86VectorTypeForVectorCall(getContext(), Ty);
1435  }
1436 
1437  bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1438  uint64_t NumMembers) const override {
1439  // FIXME: Assumes vectorcall is in use.
1440  return isX86VectorCallAggregateSmallEnough(NumMembers);
1441  }
1442 
1443 private:
1444  ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
1445  bool IsVectorCall, bool IsRegCall) const;
1446  ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
1447  const ABIArgInfo &current) const;
1448 
1449  X86AVXABILevel AVXLevel;
1450 
1451  bool IsMingw64;
1452 };
1453 
1454 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1455 public:
1456  X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1457  : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {
1458  SwiftInfo =
1459  std::make_unique<SwiftABIInfo>(CGT, /*SwiftErrorInRegister=*/true);
1460  }
1461 
1462  /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
1463  /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
1464  bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
1465 
1466  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1467  return 7;
1468  }
1469 
1470  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1471  llvm::Value *Address) const override {
1472  llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1473 
1474  // 0-15 are the 16 integer registers.
1475  // 16 is %rip.
1476  AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1477  return false;
1478  }
1479 
1480  llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1481  StringRef Constraint,
1482  llvm::Type* Ty) const override {
1483  return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1484  }
1485 
1486  bool isNoProtoCallVariadic(const CallArgList &args,
1487  const FunctionNoProtoType *fnType) const override {
1488  // The default CC on x86-64 sets %al to the number of SSA
1489  // registers used, and GCC sets this when calling an unprototyped
1490  // function, so we override the default behavior. However, don't do
1491  // that when AVX types are involved: the ABI explicitly states it is
1492  // undefined, and it doesn't work in practice because of how the ABI
1493  // defines varargs anyway.
1494  if (fnType->getCallConv() == CC_C) {
1495  bool HasAVXType = false;
1496  for (CallArgList::const_iterator
1497  it = args.begin(), ie = args.end(); it != ie; ++it) {
1498  if (getABIInfo<X86_64ABIInfo>().isPassedUsingAVXType(it->Ty)) {
1499  HasAVXType = true;
1500  break;
1501  }
1502  }
1503 
1504  if (!HasAVXType)
1505  return true;
1506  }
1507 
1508  return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
1509  }
1510 
1511  void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1512  CodeGen::CodeGenModule &CGM) const override {
1513  if (GV->isDeclaration())
1514  return;
1515  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1516  if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1517  llvm::Function *Fn = cast<llvm::Function>(GV);
1518  Fn->addFnAttr("stackrealign");
1519  }
1520 
1521  addX86InterruptAttrs(FD, GV, CGM);
1522  }
1523  }
1524 
1525  void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
1526  const FunctionDecl *Caller,
1527  const FunctionDecl *Callee, const CallArgList &Args,
1528  QualType ReturnType) const override;
1529 };
1530 } // namespace
1531 
1532 static void initFeatureMaps(const ASTContext &Ctx,
1533  llvm::StringMap<bool> &CallerMap,
1534  const FunctionDecl *Caller,
1535  llvm::StringMap<bool> &CalleeMap,
1536  const FunctionDecl *Callee) {
1537  if (CalleeMap.empty() && CallerMap.empty()) {
1538  // The caller is potentially nullptr in the case where the call isn't in a
1539  // function. In this case, the getFunctionFeatureMap ensures we just get
1540  // the TU level setting (since it cannot be modified by 'target'..
1541  Ctx.getFunctionFeatureMap(CallerMap, Caller);
1542  Ctx.getFunctionFeatureMap(CalleeMap, Callee);
1543  }
1544 }
1545 
1547  SourceLocation CallLoc,
1548  const llvm::StringMap<bool> &CallerMap,
1549  const llvm::StringMap<bool> &CalleeMap,
1550  QualType Ty, StringRef Feature,
1551  bool IsArgument) {
1552  bool CallerHasFeat = CallerMap.lookup(Feature);
1553  bool CalleeHasFeat = CalleeMap.lookup(Feature);
1554  if (!CallerHasFeat && !CalleeHasFeat)
1555  return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
1556  << IsArgument << Ty << Feature;
1557 
1558  // Mixing calling conventions here is very clearly an error.
1559  if (!CallerHasFeat || !CalleeHasFeat)
1560  return Diag.Report(CallLoc, diag::err_avx_calling_convention)
1561  << IsArgument << Ty << Feature;
1562 
1563  // Else, both caller and callee have the required feature, so there is no need
1564  // to diagnose.
1565  return false;
1566 }
1567 
1569  SourceLocation CallLoc,
1570  const llvm::StringMap<bool> &CallerMap,
1571  const llvm::StringMap<bool> &CalleeMap,
1572  QualType Ty, bool IsArgument) {
1573  bool Caller256 = CallerMap.lookup("avx512f") && !CallerMap.lookup("evex512");
1574  bool Callee256 = CalleeMap.lookup("avx512f") && !CalleeMap.lookup("evex512");
1575 
1576  // Forbid 512-bit or larger vector pass or return when we disabled ZMM
1577  // instructions.
1578  if (Caller256 || Callee256)
1579  return Diag.Report(CallLoc, diag::err_avx_calling_convention)
1580  << IsArgument << Ty << "evex512";
1581 
1582  return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
1583  "avx512f", IsArgument);
1584 }
1585 
1587  SourceLocation CallLoc,
1588  const llvm::StringMap<bool> &CallerMap,
1589  const llvm::StringMap<bool> &CalleeMap, QualType Ty,
1590  bool IsArgument) {
1591  uint64_t Size = Ctx.getTypeSize(Ty);
1592  if (Size > 256)
1593  return checkAVX512ParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
1594  IsArgument);
1595 
1596  if (Size > 128)
1597  return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
1598  IsArgument);
1599 
1600  return false;
1601 }
1602 
1603 void X86_64TargetCodeGenInfo::checkFunctionCallABI(CodeGenModule &CGM,
1604  SourceLocation CallLoc,
1605  const FunctionDecl *Caller,
1606  const FunctionDecl *Callee,
1607  const CallArgList &Args,
1608  QualType ReturnType) const {
1609  if (!Callee)
1610  return;
1611 
1612  llvm::StringMap<bool> CallerMap;
1613  llvm::StringMap<bool> CalleeMap;
1614  unsigned ArgIndex = 0;
1615 
1616  // We need to loop through the actual call arguments rather than the
1617  // function's parameters, in case this variadic.
1618  for (const CallArg &Arg : Args) {
1619  // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
1620  // additionally changes how vectors >256 in size are passed. Like GCC, we
1621  // warn when a function is called with an argument where this will change.
1622  // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
1623  // the caller and callee features are mismatched.
1624  // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
1625  // change its ABI with attribute-target after this call.
1626  if (Arg.getType()->isVectorType() &&
1627  CGM.getContext().getTypeSize(Arg.getType()) > 128) {
1628  initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
1629  QualType Ty = Arg.getType();
1630  // The CallArg seems to have desugared the type already, so for clearer
1631  // diagnostics, replace it with the type in the FunctionDecl if possible.
1632  if (ArgIndex < Callee->getNumParams())
1633  Ty = Callee->getParamDecl(ArgIndex)->getType();
1634 
1635  if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
1636  CalleeMap, Ty, /*IsArgument*/ true))
1637  return;
1638  }
1639  ++ArgIndex;
1640  }
1641 
1642  // Check return always, as we don't have a good way of knowing in codegen
1643  // whether this value is used, tail-called, etc.
1644  if (Callee->getReturnType()->isVectorType() &&
1645  CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
1646  initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
1647  checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
1648  CalleeMap, Callee->getReturnType(),
1649  /*IsArgument*/ false);
1650  }
1651 }
1652 
1653 std::string TargetCodeGenInfo::qualifyWindowsLibrary(StringRef Lib) {
1654  // If the argument does not end in .lib, automatically add the suffix.
1655  // If the argument contains a space, enclose it in quotes.
1656  // This matches the behavior of MSVC.
1657  bool Quote = Lib.contains(' ');
1658  std::string ArgStr = Quote ? "\"" : "";
1659  ArgStr += Lib;
1660  if (!Lib.ends_with_insensitive(".lib") && !Lib.ends_with_insensitive(".a"))
1661  ArgStr += ".lib";
1662  ArgStr += Quote ? "\"" : "";
1663  return ArgStr;
1664 }
1665 
1666 namespace {
1667 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1668 public:
1669  WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1670  bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
1671  unsigned NumRegisterParameters)
1672  : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
1673  Win32StructABI, NumRegisterParameters, false) {}
1674 
1675  void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1676  CodeGen::CodeGenModule &CGM) const override;
1677 
1678  void getDependentLibraryOption(llvm::StringRef Lib,
1679  llvm::SmallString<24> &Opt) const override {
1680  Opt = "/DEFAULTLIB:";
1681  Opt += qualifyWindowsLibrary(Lib);
1682  }
1683 
1684  void getDetectMismatchOption(llvm::StringRef Name,
1685  llvm::StringRef Value,
1686  llvm::SmallString<32> &Opt) const override {
1687  Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
1688  }
1689 };
1690 } // namespace
1691 
1692 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
1693  const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1694  X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
1695  if (GV->isDeclaration())
1696  return;
1697  addStackProbeTargetAttributes(D, GV, CGM);
1698 }
1699 
1700 namespace {
1701 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1702 public:
1703  WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1704  X86AVXABILevel AVXLevel)
1705  : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {
1706  SwiftInfo =
1707  std::make_unique<SwiftABIInfo>(CGT, /*SwiftErrorInRegister=*/true);
1708  }
1709 
1710  void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1711  CodeGen::CodeGenModule &CGM) const override;
1712 
1713  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1714  return 7;
1715  }
1716 
1717  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1718  llvm::Value *Address) const override {
1719  llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1720 
1721  // 0-15 are the 16 integer registers.
1722  // 16 is %rip.
1723  AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1724  return false;
1725  }
1726 
1727  void getDependentLibraryOption(llvm::StringRef Lib,
1728  llvm::SmallString<24> &Opt) const override {
1729  Opt = "/DEFAULTLIB:";
1730  Opt += qualifyWindowsLibrary(Lib);
1731  }
1732 
1733  void getDetectMismatchOption(llvm::StringRef Name,
1734  llvm::StringRef Value,
1735  llvm::SmallString<32> &Opt) const override {
1736  Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
1737  }
1738 };
1739 } // namespace
1740 
1741 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
1742  const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1744  if (GV->isDeclaration())
1745  return;
1746  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1747  if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1748  llvm::Function *Fn = cast<llvm::Function>(GV);
1749  Fn->addFnAttr("stackrealign");
1750  }
1751 
1752  addX86InterruptAttrs(FD, GV, CGM);
1753  }
1754 
1755  addStackProbeTargetAttributes(D, GV, CGM);
1756 }
1757 
1758 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1759  Class &Hi) const {
1760  // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1761  //
1762  // (a) If one of the classes is Memory, the whole argument is passed in
1763  // memory.
1764  //
1765  // (b) If X87UP is not preceded by X87, the whole argument is passed in
1766  // memory.
1767  //
1768  // (c) If the size of the aggregate exceeds two eightbytes and the first
1769  // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1770  // argument is passed in memory. NOTE: This is necessary to keep the
1771  // ABI working for processors that don't support the __m256 type.
1772  //
1773  // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1774  //
1775  // Some of these are enforced by the merging logic. Others can arise
1776  // only with unions; for example:
1777  // union { _Complex double; unsigned; }
1778  //
1779  // Note that clauses (b) and (c) were added in 0.98.
1780  //
1781  if (Hi == Memory)
1782  Lo = Memory;
1783  if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1784  Lo = Memory;
1785  if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1786  Lo = Memory;
1787  if (Hi == SSEUp && Lo != SSE)
1788  Hi = SSE;
1789 }
1790 
1791 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
1792  // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1793  // classified recursively so that always two fields are
1794  // considered. The resulting class is calculated according to
1795  // the classes of the fields in the eightbyte:
1796  //
1797  // (a) If both classes are equal, this is the resulting class.
1798  //
1799  // (b) If one of the classes is NO_CLASS, the resulting class is
1800  // the other class.
1801  //
1802  // (c) If one of the classes is MEMORY, the result is the MEMORY
1803  // class.
1804  //
1805  // (d) If one of the classes is INTEGER, the result is the
1806  // INTEGER.
1807  //
1808  // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1809  // MEMORY is used as class.
1810  //
1811  // (f) Otherwise class SSE is used.
1812 
1813  // Accum should never be memory (we should have returned) or
1814  // ComplexX87 (because this cannot be passed in a structure).
1815  assert((Accum != Memory && Accum != ComplexX87) &&
1816  "Invalid accumulated classification during merge.");
1817  if (Accum == Field || Field == NoClass)
1818  return Accum;
1819  if (Field == Memory)
1820  return Memory;
1821  if (Accum == NoClass)
1822  return Field;
1823  if (Accum == Integer || Field == Integer)
1824  return Integer;
1825  if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1826  Accum == X87 || Accum == X87Up)
1827  return Memory;
1828  return SSE;
1829 }
1830 
1831 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, Class &Lo,
1832  Class &Hi, bool isNamedArg, bool IsRegCall) const {
1833  // FIXME: This code can be simplified by introducing a simple value class for
1834  // Class pairs with appropriate constructor methods for the various
1835  // situations.
1836 
1837  // FIXME: Some of the split computations are wrong; unaligned vectors
1838  // shouldn't be passed in registers for example, so there is no chance they
1839  // can straddle an eightbyte. Verify & simplify.
1840 
1841  Lo = Hi = NoClass;
1842 
1843  Class &Current = OffsetBase < 64 ? Lo : Hi;
1844  Current = Memory;
1845 
1846  if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1847  BuiltinType::Kind k = BT->getKind();
1848 
1849  if (k == BuiltinType::Void) {
1850  Current = NoClass;
1851  } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1852  Lo = Integer;
1853  Hi = Integer;
1854  } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1855  Current = Integer;
1856  } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
1857  k == BuiltinType::Float16 || k == BuiltinType::BFloat16) {
1858  Current = SSE;
1859  } else if (k == BuiltinType::Float128) {
1860  Lo = SSE;
1861  Hi = SSEUp;
1862  } else if (k == BuiltinType::LongDouble) {
1863  const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
1864  if (LDF == &llvm::APFloat::IEEEquad()) {
1865  Lo = SSE;
1866  Hi = SSEUp;
1867  } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
1868  Lo = X87;
1869  Hi = X87Up;
1870  } else if (LDF == &llvm::APFloat::IEEEdouble()) {
1871  Current = SSE;
1872  } else
1873  llvm_unreachable("unexpected long double representation!");
1874  }
1875  // FIXME: _Decimal32 and _Decimal64 are SSE.
1876  // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
1877  return;
1878  }
1879 
1880  if (const EnumType *ET = Ty->getAs<EnumType>()) {
1881  // Classify the underlying integer type.
1882  classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
1883  return;
1884  }
1885 
1886  if (Ty->hasPointerRepresentation()) {
1887  Current = Integer;
1888  return;
1889  }
1890 
1891  if (Ty->isMemberPointerType()) {
1892  if (Ty->isMemberFunctionPointerType()) {
1893  if (Has64BitPointers) {
1894  // If Has64BitPointers, this is an {i64, i64}, so classify both
1895  // Lo and Hi now.
1896  Lo = Hi = Integer;
1897  } else {
1898  // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1899  // straddles an eightbyte boundary, Hi should be classified as well.
1900  uint64_t EB_FuncPtr = (OffsetBase) / 64;
1901  uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1902  if (EB_FuncPtr != EB_ThisAdj) {
1903  Lo = Hi = Integer;
1904  } else {
1905  Current = Integer;
1906  }
1907  }
1908  } else {
1909  Current = Integer;
1910  }
1911  return;
1912  }
1913 
1914  if (const VectorType *VT = Ty->getAs<VectorType>()) {
1915  uint64_t Size = getContext().getTypeSize(VT);
1916  if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
1917  // gcc passes the following as integer:
1918  // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
1919  // 2 bytes - <2 x char>, <1 x short>
1920  // 1 byte - <1 x char>
1921  Current = Integer;
1922 
1923  // If this type crosses an eightbyte boundary, it should be
1924  // split.
1925  uint64_t EB_Lo = (OffsetBase) / 64;
1926  uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
1927  if (EB_Lo != EB_Hi)
1928  Hi = Lo;
1929  } else if (Size == 64) {
1930  QualType ElementType = VT->getElementType();
1931 
1932  // gcc passes <1 x double> in memory. :(
1933  if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
1934  return;
1935 
1936  // gcc passes <1 x long long> as SSE but clang used to unconditionally
1937  // pass them as integer. For platforms where clang is the de facto
1938  // platform compiler, we must continue to use integer.
1939  if (!classifyIntegerMMXAsSSE() &&
1940  (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
1941  ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1942  ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
1943  ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
1944  Current = Integer;
1945  else
1946  Current = SSE;
1947 
1948  // If this type crosses an eightbyte boundary, it should be
1949  // split.
1950  if (OffsetBase && OffsetBase != 64)
1951  Hi = Lo;
1952  } else if (Size == 128 ||
1953  (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
1954  QualType ElementType = VT->getElementType();
1955 
1956  // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
1957  if (passInt128VectorsInMem() && Size != 128 &&
1958  (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
1959  ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
1960  return;
1961 
1962  // Arguments of 256-bits are split into four eightbyte chunks. The
1963  // least significant one belongs to class SSE and all the others to class
1964  // SSEUP. The original Lo and Hi design considers that types can't be
1965  // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1966  // This design isn't correct for 256-bits, but since there're no cases
1967  // where the upper parts would need to be inspected, avoid adding
1968  // complexity and just consider Hi to match the 64-256 part.
1969  //
1970  // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1971  // registers if they are "named", i.e. not part of the "..." of a
1972  // variadic function.
1973  //
1974  // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
1975  // split into eight eightbyte chunks, one SSE and seven SSEUP.
1976  Lo = SSE;
1977  Hi = SSEUp;
1978  }
1979  return;
1980  }
1981 
1982  if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
1983  QualType ET = getContext().getCanonicalType(CT->getElementType());
1984 
1985  uint64_t Size = getContext().getTypeSize(Ty);
1986  if (ET->isIntegralOrEnumerationType()) {
1987  if (Size <= 64)
1988  Current = Integer;
1989  else if (Size <= 128)
1990  Lo = Hi = Integer;
1991  } else if (ET->isFloat16Type() || ET == getContext().FloatTy ||
1992  ET->isBFloat16Type()) {
1993  Current = SSE;
1994  } else if (ET == getContext().DoubleTy) {
1995  Lo = Hi = SSE;
1996  } else if (ET == getContext().LongDoubleTy) {
1997  const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
1998  if (LDF == &llvm::APFloat::IEEEquad())
1999  Current = Memory;
2000  else if (LDF == &llvm::APFloat::x87DoubleExtended())
2001  Current = ComplexX87;
2002  else if (LDF == &llvm::APFloat::IEEEdouble())
2003  Lo = Hi = SSE;
2004  else
2005  llvm_unreachable("unexpected long double representation!");
2006  }
2007 
2008  // If this complex type crosses an eightbyte boundary then it
2009  // should be split.
2010  uint64_t EB_Real = (OffsetBase) / 64;
2011  uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2012  if (Hi == NoClass && EB_Real != EB_Imag)
2013  Hi = Lo;
2014 
2015  return;
2016  }
2017 
2018  if (const auto *EITy = Ty->getAs<BitIntType>()) {
2019  if (EITy->getNumBits() <= 64)
2020  Current = Integer;
2021  else if (EITy->getNumBits() <= 128)
2022  Lo = Hi = Integer;
2023  // Larger values need to get passed in memory.
2024  return;
2025  }
2026 
2027  if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2028  // Arrays are treated like structures.
2029 
2030  uint64_t Size = getContext().getTypeSize(Ty);
2031 
2032  // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2033  // than eight eightbytes, ..., it has class MEMORY.
2034  // regcall ABI doesn't have limitation to an object. The only limitation
2035  // is the free registers, which will be checked in computeInfo.
2036  if (!IsRegCall && Size > 512)
2037  return;
2038 
2039  // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2040  // fields, it has class MEMORY.
2041  //
2042  // Only need to check alignment of array base.
2043  if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2044  return;
2045 
2046  // Otherwise implement simplified merge. We could be smarter about
2047  // this, but it isn't worth it and would be harder to verify.
2048  Current = NoClass;
2049  uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2050  uint64_t ArraySize = AT->getZExtSize();
2051 
2052  // The only case a 256-bit wide vector could be used is when the array
2053  // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2054  // to work for sizes wider than 128, early check and fallback to memory.
2055  //
2056  if (Size > 128 &&
2057  (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2058  return;
2059 
2060  for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2061  Class FieldLo, FieldHi;
2062  classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2063  Lo = merge(Lo, FieldLo);
2064  Hi = merge(Hi, FieldHi);
2065  if (Lo == Memory || Hi == Memory)
2066  break;
2067  }
2068 
2069  postMerge(Size, Lo, Hi);
2070  assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2071  return;
2072  }
2073 
2074  if (const RecordType *RT = Ty->getAs<RecordType>()) {
2075  uint64_t Size = getContext().getTypeSize(Ty);
2076 
2077  // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2078  // than eight eightbytes, ..., it has class MEMORY.
2079  if (Size > 512)
2080  return;
2081 
2082  // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2083  // copy constructor or a non-trivial destructor, it is passed by invisible
2084  // reference.
2085  if (getRecordArgABI(RT, getCXXABI()))
2086  return;
2087 
2088  const RecordDecl *RD = RT->getDecl();
2089 
2090  // Assume variable sized types are passed in memory.
2091  if (RD->hasFlexibleArrayMember())
2092  return;
2093 
2094  const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2095 
2096  // Reset Lo class, this will be recomputed.
2097  Current = NoClass;
2098 
2099  // If this is a C++ record, classify the bases first.
2100  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2101  for (const auto &I : CXXRD->bases()) {
2102  assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2103  "Unexpected base class!");
2104  const auto *Base =
2105  cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2106 
2107  // Classify this field.
2108  //
2109  // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2110  // single eightbyte, each is classified separately. Each eightbyte gets
2111  // initialized to class NO_CLASS.
2112  Class FieldLo, FieldHi;
2113  uint64_t Offset =
2114  OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2115  classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2116  Lo = merge(Lo, FieldLo);
2117  Hi = merge(Hi, FieldHi);
2118  if (Lo == Memory || Hi == Memory) {
2119  postMerge(Size, Lo, Hi);
2120  return;
2121  }
2122  }
2123  }
2124 
2125  // Classify the fields one at a time, merging the results.
2126  unsigned idx = 0;
2127  bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
2129  getContext().getTargetInfo().getTriple().isPS();
2130  bool IsUnion = RT->isUnionType() && !UseClang11Compat;
2131 
2132  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2133  i != e; ++i, ++idx) {
2134  uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2135  bool BitField = i->isBitField();
2136 
2137  // Ignore padding bit-fields.
2138  if (BitField && i->isUnnamedBitField())
2139  continue;
2140 
2141  // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2142  // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
2143  //
2144  // The only case a 256-bit or a 512-bit wide vector could be used is when
2145  // the struct contains a single 256-bit or 512-bit element. Early check
2146  // and fallback to memory.
2147  //
2148  // FIXME: Extended the Lo and Hi logic properly to work for size wider
2149  // than 128.
2150  if (Size > 128 &&
2151  ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
2152  Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2153  Lo = Memory;
2154  postMerge(Size, Lo, Hi);
2155  return;
2156  }
2157 
2158  bool IsInMemory =
2159  Offset % getContext().getTypeAlign(i->getType().getCanonicalType());
2160  // Note, skip this test for bit-fields, see below.
2161  if (!BitField && IsInMemory) {
2162  Lo = Memory;
2163  postMerge(Size, Lo, Hi);
2164  return;
2165  }
2166 
2167  // Classify this field.
2168  //
2169  // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2170  // exceeds a single eightbyte, each is classified
2171  // separately. Each eightbyte gets initialized to class
2172  // NO_CLASS.
2173  Class FieldLo, FieldHi;
2174 
2175  // Bit-fields require special handling, they do not force the
2176  // structure to be passed in memory even if unaligned, and
2177  // therefore they can straddle an eightbyte.
2178  if (BitField) {
2179  assert(!i->isUnnamedBitField());
2180  uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2181  uint64_t Size = i->getBitWidthValue(getContext());
2182 
2183  uint64_t EB_Lo = Offset / 64;
2184  uint64_t EB_Hi = (Offset + Size - 1) / 64;
2185 
2186  if (EB_Lo) {
2187  assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2188  FieldLo = NoClass;
2189  FieldHi = Integer;
2190  } else {
2191  FieldLo = Integer;
2192  FieldHi = EB_Hi ? Integer : NoClass;
2193  }
2194  } else
2195  classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
2196  Lo = merge(Lo, FieldLo);
2197  Hi = merge(Hi, FieldHi);
2198  if (Lo == Memory || Hi == Memory)
2199  break;
2200  }
2201 
2202  postMerge(Size, Lo, Hi);
2203  }
2204 }
2205 
2206 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
2207  // If this is a scalar LLVM value then assume LLVM will pass it in the right
2208  // place naturally.
2209  if (!isAggregateTypeForABI(Ty)) {
2210  // Treat an enum type as its underlying type.
2211  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2212  Ty = EnumTy->getDecl()->getIntegerType();
2213 
2214  if (Ty->isBitIntType())
2215  return getNaturalAlignIndirect(Ty);
2216 
2217  return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
2218  : ABIArgInfo::getDirect());
2219  }
2220 
2221  return getNaturalAlignIndirect(Ty);
2222 }
2223 
2224 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2225  if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2226  uint64_t Size = getContext().getTypeSize(VecTy);
2227  unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
2228  if (Size <= 64 || Size > LargestVector)
2229  return true;
2230  QualType EltTy = VecTy->getElementType();
2231  if (passInt128VectorsInMem() &&
2232  (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
2233  EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
2234  return true;
2235  }
2236 
2237  return false;
2238 }
2239 
2240 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2241  unsigned freeIntRegs) const {
2242  // If this is a scalar LLVM value then assume LLVM will pass it in the right
2243  // place naturally.
2244  //
2245  // This assumption is optimistic, as there could be free registers available
2246  // when we need to pass this argument in memory, and LLVM could try to pass
2247  // the argument in the free register. This does not seem to happen currently,
2248  // but this code would be much safer if we could mark the argument with
2249  // 'onstack'. See PR12193.
2250  if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
2251  !Ty->isBitIntType()) {
2252  // Treat an enum type as its underlying type.
2253  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2254  Ty = EnumTy->getDecl()->getIntegerType();
2255 
2256  return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
2257  : ABIArgInfo::getDirect());
2258  }
2259 
2260  if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
2261  return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
2262 
2263  // Compute the byval alignment. We specify the alignment of the byval in all
2264  // cases so that the mid-level optimizer knows the alignment of the byval.
2265  unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
2266 
2267  // Attempt to avoid passing indirect results using byval when possible. This
2268  // is important for good codegen.
2269  //
2270  // We do this by coercing the value into a scalar type which the backend can
2271  // handle naturally (i.e., without using byval).
2272  //
2273  // For simplicity, we currently only do this when we have exhausted all of the
2274  // free integer registers. Doing this when there are free integer registers
2275  // would require more care, as we would have to ensure that the coerced value
2276  // did not claim the unused register. That would require either reording the
2277  // arguments to the function (so that any subsequent inreg values came first),
2278  // or only doing this optimization when there were no following arguments that
2279  // might be inreg.
2280  //
2281  // We currently expect it to be rare (particularly in well written code) for
2282  // arguments to be passed on the stack when there are still free integer
2283  // registers available (this would typically imply large structs being passed
2284  // by value), so this seems like a fair tradeoff for now.
2285  //
2286  // We can revisit this if the backend grows support for 'onstack' parameter
2287  // attributes. See PR12193.
2288  if (freeIntRegs == 0) {
2289  uint64_t Size = getContext().getTypeSize(Ty);
2290 
2291  // If this type fits in an eightbyte, coerce it into the matching integral
2292  // type, which will end up on the stack (with alignment 8).
2293  if (Align == 8 && Size <= 64)
2294  return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2295  Size));
2296  }
2297 
2299 }
2300 
2301 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
2302 /// register. Pick an LLVM IR type that will be passed as a vector register.
2303 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
2304  // Wrapper structs/arrays that only contain vectors are passed just like
2305  // vectors; strip them off if present.
2306  if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2307  Ty = QualType(InnerTy, 0);
2308 
2309  llvm::Type *IRType = CGT.ConvertType(Ty);
2310  if (isa<llvm::VectorType>(IRType)) {
2311  // Don't pass vXi128 vectors in their native type, the backend can't
2312  // legalize them.
2313  if (passInt128VectorsInMem() &&
2314  cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
2315  // Use a vXi64 vector.
2316  uint64_t Size = getContext().getTypeSize(Ty);
2317  return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
2318  Size / 64);
2319  }
2320 
2321  return IRType;
2322  }
2323 
2324  if (IRType->getTypeID() == llvm::Type::FP128TyID)
2325  return IRType;
2326 
2327  // We couldn't find the preferred IR vector type for 'Ty'.
2328  uint64_t Size = getContext().getTypeSize(Ty);
2329  assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
2330 
2331 
2332  // Return a LLVM IR vector type based on the size of 'Ty'.
2333  return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2334  Size / 64);
2335 }
2336 
2337 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
2338 /// is known to either be off the end of the specified type or being in
2339 /// alignment padding. The user type specified is known to be at most 128 bits
2340 /// in size, and have passed through X86_64ABIInfo::classify with a successful
2341 /// classification that put one of the two halves in the INTEGER class.
2342 ///
2343 /// It is conservatively correct to return false.
2344 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2345  unsigned EndBit, ASTContext &Context) {
2346  // If the bytes being queried are off the end of the type, there is no user
2347  // data hiding here. This handles analysis of builtins, vectors and other
2348  // types that don't contain interesting padding.
2349  unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2350  if (TySize <= StartBit)
2351  return true;
2352 
2353  if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2354  unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2355  unsigned NumElts = (unsigned)AT->getZExtSize();
2356 
2357  // Check each element to see if the element overlaps with the queried range.
2358  for (unsigned i = 0; i != NumElts; ++i) {
2359  // If the element is after the span we care about, then we're done..
2360  unsigned EltOffset = i*EltSize;
2361  if (EltOffset >= EndBit) break;
2362 
2363  unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2364  if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2365  EndBit-EltOffset, Context))
2366  return false;
2367  }
2368  // If it overlaps no elements, then it is safe to process as padding.
2369  return true;
2370  }
2371 
2372  if (const RecordType *RT = Ty->getAs<RecordType>()) {
2373  const RecordDecl *RD = RT->getDecl();
2374  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2375 
2376  // If this is a C++ record, check the bases first.
2377  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2378  for (const auto &I : CXXRD->bases()) {
2379  assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2380  "Unexpected base class!");
2381  const auto *Base =
2382  cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2383 
2384  // If the base is after the span we care about, ignore it.
2385  unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
2386  if (BaseOffset >= EndBit) continue;
2387 
2388  unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
2389  if (!BitsContainNoUserData(I.getType(), BaseStart,
2390  EndBit-BaseOffset, Context))
2391  return false;
2392  }
2393  }
2394 
2395  // Verify that no field has data that overlaps the region of interest. Yes
2396  // this could be sped up a lot by being smarter about queried fields,
2397  // however we're only looking at structs up to 16 bytes, so we don't care
2398  // much.
2399  unsigned idx = 0;
2400  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2401  i != e; ++i, ++idx) {
2402  unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
2403 
2404  // If we found a field after the region we care about, then we're done.
2405  if (FieldOffset >= EndBit) break;
2406 
2407  unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2408  if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2409  Context))
2410  return false;
2411  }
2412 
2413  // If nothing in this record overlapped the area of interest, then we're
2414  // clean.
2415  return true;
2416  }
2417 
2418  return false;
2419 }
2420 
2421 /// getFPTypeAtOffset - Return a floating point type at the specified offset.
2422 static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2423  const llvm::DataLayout &TD) {
2424  if (IROffset == 0 && IRType->isFloatingPointTy())
2425  return IRType;
2426 
2427  // If this is a struct, recurse into the field at the specified offset.
2428  if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
2429  if (!STy->getNumContainedTypes())
2430  return nullptr;
2431 
2432  const llvm::StructLayout *SL = TD.getStructLayout(STy);
2433  unsigned Elt = SL->getElementContainingOffset(IROffset);
2434  IROffset -= SL->getElementOffset(Elt);
2435  return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
2436  }
2437 
2438  // If this is an array, recurse into the field at the specified offset.
2439  if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2440  llvm::Type *EltTy = ATy->getElementType();
2441  unsigned EltSize = TD.getTypeAllocSize(EltTy);
2442  IROffset -= IROffset / EltSize * EltSize;
2443  return getFPTypeAtOffset(EltTy, IROffset, TD);
2444  }
2445 
2446  return nullptr;
2447 }
2448 
2449 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2450 /// low 8 bytes of an XMM register, corresponding to the SSE class.
2451 llvm::Type *X86_64ABIInfo::
2452 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2453  QualType SourceTy, unsigned SourceOffset) const {
2454  const llvm::DataLayout &TD = getDataLayout();
2455  unsigned SourceSize =
2456  (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
2457  llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
2458  if (!T0 || T0->isDoubleTy())
2459  return llvm::Type::getDoubleTy(getVMContext());
2460 
2461  // Get the adjacent FP type.
2462  llvm::Type *T1 = nullptr;
2463  unsigned T0Size = TD.getTypeAllocSize(T0);
2464  if (SourceSize > T0Size)
2465  T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
2466  if (T1 == nullptr) {
2467  // Check if IRType is a half/bfloat + float. float type will be in IROffset+4 due
2468  // to its alignment.
2469  if (T0->is16bitFPTy() && SourceSize > 4)
2470  T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
2471  // If we can't get a second FP type, return a simple half or float.
2472  // avx512fp16-abi.c:pr51813_2 shows it works to return float for
2473  // {float, i8} too.
2474  if (T1 == nullptr)
2475  return T0;
2476  }
2477 
2478  if (T0->isFloatTy() && T1->isFloatTy())
2479  return llvm::FixedVectorType::get(T0, 2);
2480 
2481  if (T0->is16bitFPTy() && T1->is16bitFPTy()) {
2482  llvm::Type *T2 = nullptr;
2483  if (SourceSize > 4)
2484  T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
2485  if (T2 == nullptr)
2486  return llvm::FixedVectorType::get(T0, 2);
2487  return llvm::FixedVectorType::get(T0, 4);
2488  }
2489 
2490  if (T0->is16bitFPTy() || T1->is16bitFPTy())
2491  return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
2492 
2493  return llvm::Type::getDoubleTy(getVMContext());
2494 }
2495 
2496 
2497 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2498 /// an 8-byte GPR. This means that we either have a scalar or we are talking
2499 /// about the high or low part of an up-to-16-byte struct. This routine picks
2500 /// the best LLVM IR type to represent this, which may be i64 or may be anything
2501 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2502 /// etc).
2503 ///
2504 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2505 /// the source type. IROffset is an offset in bytes into the LLVM IR type that
2506 /// the 8-byte value references. PrefType may be null.
2507 ///
2508 /// SourceTy is the source-level type for the entire argument. SourceOffset is
2509 /// an offset into this that we're processing (which is always either 0 or 8).
2510 ///
2511 llvm::Type *X86_64ABIInfo::
2512 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2513  QualType SourceTy, unsigned SourceOffset) const {
2514  // If we're dealing with an un-offset LLVM IR type, then it means that we're
2515  // returning an 8-byte unit starting with it. See if we can safely use it.
2516  if (IROffset == 0) {
2517  // Pointers and int64's always fill the 8-byte unit.
2518  if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2519  IRType->isIntegerTy(64))
2520  return IRType;
2521 
2522  // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2523  // goodness in the source type is just tail padding. This is allowed to
2524  // kick in for struct {double,int} on the int, but not on
2525  // struct{double,int,int} because we wouldn't return the second int. We
2526  // have to do this analysis on the source type because we can't depend on
2527  // unions being lowered a specific way etc.
2528  if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
2529  IRType->isIntegerTy(32) ||
2530  (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2531  unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2532  cast<llvm::IntegerType>(IRType)->getBitWidth();
2533 
2534  if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2535  SourceOffset*8+64, getContext()))
2536  return IRType;
2537  }
2538  }
2539 
2540  if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
2541  // If this is a struct, recurse into the field at the specified offset.
2542  const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
2543  if (IROffset < SL->getSizeInBytes()) {
2544  unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2545  IROffset -= SL->getElementOffset(FieldIdx);
2546 
2547  return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2548  SourceTy, SourceOffset);
2549  }
2550  }
2551 
2552  if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2553  llvm::Type *EltTy = ATy->getElementType();
2554  unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
2555  unsigned EltOffset = IROffset/EltSize*EltSize;
2556  return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2557  SourceOffset);
2558  }
2559 
2560  // Okay, we don't have any better idea of what to pass, so we pass this in an
2561  // integer register that isn't too big to fit the rest of the struct.
2562  unsigned TySizeInBytes =
2563  (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
2564 
2565  assert(TySizeInBytes != SourceOffset && "Empty field?");
2566 
2567  // It is always safe to classify this as an integer type up to i64 that
2568  // isn't larger than the structure.
2569  return llvm::IntegerType::get(getVMContext(),
2570  std::min(TySizeInBytes-SourceOffset, 8U)*8);
2571 }
2572 
2573 
2574 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2575 /// be used as elements of a two register pair to pass or return, return a
2576 /// first class aggregate to represent them. For example, if the low part of
2577 /// a by-value argument should be passed as i32* and the high part as float,
2578 /// return {i32*, float}.
2579 static llvm::Type *
2580 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
2581  const llvm::DataLayout &TD) {
2582  // In order to correctly satisfy the ABI, we need to the high part to start
2583  // at offset 8. If the high and low parts we inferred are both 4-byte types
2584  // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2585  // the second element at offset 8. Check for this:
2586  unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2587  llvm::Align HiAlign = TD.getABITypeAlign(Hi);
2588  unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
2589  assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
2590 
2591  // To handle this, we have to increase the size of the low part so that the
2592  // second element will start at an 8 byte offset. We can't increase the size
2593  // of the second element because it might make us access off the end of the
2594  // struct.
2595  if (HiStart != 8) {
2596  // There are usually two sorts of types the ABI generation code can produce
2597  // for the low part of a pair that aren't 8 bytes in size: half, float or
2598  // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2599  // NaCl).
2600  // Promote these to a larger type.
2601  if (Lo->isHalfTy() || Lo->isFloatTy())
2602  Lo = llvm::Type::getDoubleTy(Lo->getContext());
2603  else {
2604  assert((Lo->isIntegerTy() || Lo->isPointerTy())
2605  && "Invalid/unknown lo type");
2606  Lo = llvm::Type::getInt64Ty(Lo->getContext());
2607  }
2608  }
2609 
2610  llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
2611 
2612  // Verify that the second element is at an 8-byte offset.
2613  assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2614  "Invalid x86-64 argument pair!");
2615  return Result;
2616 }
2617 
2619 classifyReturnType(QualType RetTy) const {
2620  // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2621  // classification algorithm.
2622  X86_64ABIInfo::Class Lo, Hi;
2623  classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
2624 
2625  // Check some invariants.
2626  assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2627  assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2628 
2629  llvm::Type *ResType = nullptr;
2630  switch (Lo) {
2631  case NoClass:
2632  if (Hi == NoClass)
2633  return ABIArgInfo::getIgnore();
2634  // If the low part is just padding, it takes no register, leave ResType
2635  // null.
2636  assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2637  "Unknown missing lo part");
2638  break;
2639 
2640  case SSEUp:
2641  case X87Up:
2642  llvm_unreachable("Invalid classification for lo word.");
2643 
2644  // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2645  // hidden argument.
2646  case Memory:
2647  return getIndirectReturnResult(RetTy);
2648 
2649  // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2650  // available register of the sequence %rax, %rdx is used.
2651  case Integer:
2652  ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
2653 
2654  // If we have a sign or zero extended integer, make sure to return Extend
2655  // so that the parameter gets the right LLVM IR attributes.
2656  if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2657  // Treat an enum type as its underlying type.
2658  if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2659  RetTy = EnumTy->getDecl()->getIntegerType();
2660 
2661  if (RetTy->isIntegralOrEnumerationType() &&
2662  isPromotableIntegerTypeForABI(RetTy))
2663  return ABIArgInfo::getExtend(RetTy);
2664  }
2665  break;
2666 
2667  // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2668  // available SSE register of the sequence %xmm0, %xmm1 is used.
2669  case SSE:
2670  ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
2671  break;
2672 
2673  // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2674  // returned on the X87 stack in %st0 as 80-bit x87 number.
2675  case X87:
2676  ResType = llvm::Type::getX86_FP80Ty(getVMContext());
2677  break;
2678 
2679  // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2680  // part of the value is returned in %st0 and the imaginary part in
2681  // %st1.
2682  case ComplexX87:
2683  assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
2684  ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
2685  llvm::Type::getX86_FP80Ty(getVMContext()));
2686  break;
2687  }
2688 
2689  llvm::Type *HighPart = nullptr;
2690  switch (Hi) {
2691  // Memory was handled previously and X87 should
2692  // never occur as a hi class.
2693  case Memory:
2694  case X87:
2695  llvm_unreachable("Invalid classification for hi word.");
2696 
2697  case ComplexX87: // Previously handled.
2698  case NoClass:
2699  break;
2700 
2701  case Integer:
2702  HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2703  if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2704  return ABIArgInfo::getDirect(HighPart, 8);
2705  break;
2706  case SSE:
2707  HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2708  if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2709  return ABIArgInfo::getDirect(HighPart, 8);
2710  break;
2711 
2712  // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
2713  // is passed in the next available eightbyte chunk if the last used
2714  // vector register.
2715  //
2716  // SSEUP should always be preceded by SSE, just widen.
2717  case SSEUp:
2718  assert(Lo == SSE && "Unexpected SSEUp classification.");
2719  ResType = GetByteVectorType(RetTy);
2720  break;
2721 
2722  // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2723  // returned together with the previous X87 value in %st0.
2724  case X87Up:
2725  // If X87Up is preceded by X87, we don't need to do
2726  // anything. However, in some cases with unions it may not be
2727  // preceded by X87. In such situations we follow gcc and pass the
2728  // extra bits in an SSE reg.
2729  if (Lo != X87) {
2730  HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2731  if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2732  return ABIArgInfo::getDirect(HighPart, 8);
2733  }
2734  break;
2735  }
2736 
2737  // If a high part was specified, merge it together with the low part. It is
2738  // known to pass in the high eightbyte of the result. We do this by forming a
2739  // first class struct aggregate with the high and low part: {low, high}
2740  if (HighPart)
2741  ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
2742 
2743  return ABIArgInfo::getDirect(ResType);
2744 }
2745 
2746 ABIArgInfo
2747 X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2748  unsigned &neededInt, unsigned &neededSSE,
2749  bool isNamedArg, bool IsRegCall) const {
2751 
2752  X86_64ABIInfo::Class Lo, Hi;
2753  classify(Ty, 0, Lo, Hi, isNamedArg, IsRegCall);
2754 
2755  // Check some invariants.
2756  // FIXME: Enforce these by construction.
2757  assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2758  assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2759 
2760  neededInt = 0;
2761  neededSSE = 0;
2762  llvm::Type *ResType = nullptr;
2763  switch (Lo) {
2764  case NoClass:
2765  if (Hi == NoClass)
2766  return ABIArgInfo::getIgnore();
2767  // If the low part is just padding, it takes no register, leave ResType
2768  // null.
2769  assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2770  "Unknown missing lo part");
2771  break;
2772 
2773  // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2774  // on the stack.
2775  case Memory:
2776 
2777  // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2778  // COMPLEX_X87, it is passed in memory.
2779  case X87:
2780  case ComplexX87:
2781  if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
2782  ++neededInt;
2783  return getIndirectResult(Ty, freeIntRegs);
2784 
2785  case SSEUp:
2786  case X87Up:
2787  llvm_unreachable("Invalid classification for lo word.");
2788 
2789  // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2790  // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2791  // and %r9 is used.
2792  case Integer:
2793  ++neededInt;
2794 
2795  // Pick an 8-byte type based on the preferred type.
2796  ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
2797 
2798  // If we have a sign or zero extended integer, make sure to return Extend
2799  // so that the parameter gets the right LLVM IR attributes.
2800  if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2801  // Treat an enum type as its underlying type.
2802  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2803  Ty = EnumTy->getDecl()->getIntegerType();
2804 
2805  if (Ty->isIntegralOrEnumerationType() &&
2806  isPromotableIntegerTypeForABI(Ty))
2807  return ABIArgInfo::getExtend(Ty);
2808  }
2809 
2810  break;
2811 
2812  // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2813  // available SSE register is used, the registers are taken in the
2814  // order from %xmm0 to %xmm7.
2815  case SSE: {
2816  llvm::Type *IRType = CGT.ConvertType(Ty);
2817  ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
2818  ++neededSSE;
2819  break;
2820  }
2821  }
2822 
2823  llvm::Type *HighPart = nullptr;
2824  switch (Hi) {
2825  // Memory was handled previously, ComplexX87 and X87 should
2826  // never occur as hi classes, and X87Up must be preceded by X87,
2827  // which is passed in memory.
2828  case Memory:
2829  case X87:
2830  case ComplexX87:
2831  llvm_unreachable("Invalid classification for hi word.");
2832 
2833  case NoClass: break;
2834 
2835  case Integer:
2836  ++neededInt;
2837  // Pick an 8-byte type based on the preferred type.
2838  HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2839 
2840  if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2841  return ABIArgInfo::getDirect(HighPart, 8);
2842  break;
2843 
2844  // X87Up generally doesn't occur here (long double is passed in
2845  // memory), except in situations involving unions.
2846  case X87Up:
2847  case SSE:
2848  ++neededSSE;
2849  HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2850 
2851  if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2852  return ABIArgInfo::getDirect(HighPart, 8);
2853  break;
2854 
2855  // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2856  // eightbyte is passed in the upper half of the last used SSE
2857  // register. This only happens when 128-bit vectors are passed.
2858  case SSEUp:
2859  assert(Lo == SSE && "Unexpected SSEUp classification");
2860  ResType = GetByteVectorType(Ty);
2861  break;
2862  }
2863 
2864  // If a high part was specified, merge it together with the low part. It is
2865  // known to pass in the high eightbyte of the result. We do this by forming a
2866  // first class struct aggregate with the high and low part: {low, high}
2867  if (HighPart)
2868  ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
2869 
2870  return ABIArgInfo::getDirect(ResType);
2871 }
2872 
2873 ABIArgInfo
2874 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2875  unsigned &NeededSSE,
2876  unsigned &MaxVectorWidth) const {
2877  auto RT = Ty->getAs<RecordType>();
2878  assert(RT && "classifyRegCallStructType only valid with struct types");
2879 
2880  if (RT->getDecl()->hasFlexibleArrayMember())
2881  return getIndirectReturnResult(Ty);
2882 
2883  // Sum up bases
2884  if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2885  if (CXXRD->isDynamicClass()) {
2886  NeededInt = NeededSSE = 0;
2887  return getIndirectReturnResult(Ty);
2888  }
2889 
2890  for (const auto &I : CXXRD->bases())
2891  if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE,
2892  MaxVectorWidth)
2893  .isIndirect()) {
2894  NeededInt = NeededSSE = 0;
2895  return getIndirectReturnResult(Ty);
2896  }
2897  }
2898 
2899  // Sum up members
2900  for (const auto *FD : RT->getDecl()->fields()) {
2901  QualType MTy = FD->getType();
2902  if (MTy->isRecordType() && !MTy->isUnionType()) {
2903  if (classifyRegCallStructTypeImpl(MTy, NeededInt, NeededSSE,
2904  MaxVectorWidth)
2905  .isIndirect()) {
2906  NeededInt = NeededSSE = 0;
2907  return getIndirectReturnResult(Ty);
2908  }
2909  } else {
2910  unsigned LocalNeededInt, LocalNeededSSE;
2911  if (classifyArgumentType(MTy, UINT_MAX, LocalNeededInt, LocalNeededSSE,
2912  true, true)
2913  .isIndirect()) {
2914  NeededInt = NeededSSE = 0;
2915  return getIndirectReturnResult(Ty);
2916  }
2917  if (const auto *AT = getContext().getAsConstantArrayType(MTy))
2918  MTy = AT->getElementType();
2919  if (const auto *VT = MTy->getAs<VectorType>())
2920  if (getContext().getTypeSize(VT) > MaxVectorWidth)
2921  MaxVectorWidth = getContext().getTypeSize(VT);
2922  NeededInt += LocalNeededInt;
2923  NeededSSE += LocalNeededSSE;
2924  }
2925  }
2926 
2927  return ABIArgInfo::getDirect();
2928 }
2929 
2930 ABIArgInfo
2931 X86_64ABIInfo::classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2932  unsigned &NeededSSE,
2933  unsigned &MaxVectorWidth) const {
2934 
2935  NeededInt = 0;
2936  NeededSSE = 0;
2937  MaxVectorWidth = 0;
2938 
2939  return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE,
2940  MaxVectorWidth);
2941 }
2942 
2943 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2944  ASTContext &Context = getContext();
2945  if (doOpenCLClassification(FI, Context))
2946  return;
2947 
2948  const unsigned CallingConv = FI.getCallingConvention();
2949  // It is possible to force Win64 calling convention on any x86_64 target by
2950  // using __attribute__((ms_abi)). In such case to correctly emit Win64
2951  // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
2952  if (CallingConv == llvm::CallingConv::Win64) {
2953  WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
2954  Win64ABIInfo.computeInfo(FI);
2955  return;
2956  }
2957 
2958  bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
2959 
2960  // Keep track of the number of assigned registers.
2961  unsigned FreeIntRegs = IsRegCall ? 11 : 6;
2962  unsigned FreeSSERegs = IsRegCall ? 16 : 8;
2963  unsigned NeededInt = 0, NeededSSE = 0, MaxVectorWidth = 0;
2964 
2965  if (!::classifyReturnType(getCXXABI(), FI, *this)) {
2966  if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
2967  !FI.getReturnType()->getTypePtr()->isUnionType()) {
2968  FI.getReturnInfo() = classifyRegCallStructType(
2969  FI.getReturnType(), NeededInt, NeededSSE, MaxVectorWidth);
2970  if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
2971  FreeIntRegs -= NeededInt;
2972  FreeSSERegs -= NeededSSE;
2973  } else {
2974  FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
2975  }
2976  } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
2977  getContext().getCanonicalType(FI.getReturnType()
2978  ->getAs<ComplexType>()
2979  ->getElementType()) ==
2980  getContext().LongDoubleTy)
2981  // Complex Long Double Type is passed in Memory when Regcall
2982  // calling convention is used.
2983  FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
2984  else
2986  }
2987 
2988  // If the return value is indirect, then the hidden argument is consuming one
2989  // integer register.
2990  if (FI.getReturnInfo().isIndirect())
2991  --FreeIntRegs;
2992  else if (NeededSSE && MaxVectorWidth > 0)
2993  FI.setMaxVectorWidth(MaxVectorWidth);
2994 
2995  // The chain argument effectively gives us another free register.
2996  if (FI.isChainCall())
2997  ++FreeIntRegs;
2998 
2999  unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3000  // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3001  // get assigned (in left-to-right order) for passing as follows...
3002  unsigned ArgNo = 0;
3003  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3004  it != ie; ++it, ++ArgNo) {
3005  bool IsNamedArg = ArgNo < NumRequiredArgs;
3006 
3007  if (IsRegCall && it->type->isStructureOrClassType())
3008  it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE,
3009  MaxVectorWidth);
3010  else
3011  it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3012  NeededSSE, IsNamedArg);
3013 
3014  // AMD64-ABI 3.2.3p3: If there are no registers available for any
3015  // eightbyte of an argument, the whole argument is passed on the
3016  // stack. If registers have already been assigned for some
3017  // eightbytes of such an argument, the assignments get reverted.
3018  if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3019  FreeIntRegs -= NeededInt;
3020  FreeSSERegs -= NeededSSE;
3021  if (MaxVectorWidth > FI.getMaxVectorWidth())
3022  FI.setMaxVectorWidth(MaxVectorWidth);
3023  } else {
3024  it->info = getIndirectResult(it->type, FreeIntRegs);
3025  }
3026  }
3027 }
3028 
3030  Address VAListAddr, QualType Ty) {
3031  Address overflow_arg_area_p =
3032  CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
3033  llvm::Value *overflow_arg_area =
3034  CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3035 
3036  // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3037  // byte boundary if alignment needed by type exceeds 8 byte boundary.
3038  // It isn't stated explicitly in the standard, but in practice we use
3039  // alignment greater than 16 where necessary.
3040  CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3041  if (Align > CharUnits::fromQuantity(8)) {
3042  overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3043  Align);
3044  }
3045 
3046  // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3047  llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3048  llvm::Value *Res = overflow_arg_area;
3049 
3050  // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3051  // l->overflow_arg_area + sizeof(type).
3052  // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3053  // an 8 byte boundary.
3054 
3055  uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3056  llvm::Value *Offset =
3057  llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
3058  overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
3059  Offset, "overflow_arg_area.next");
3060  CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3061 
3062  // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3063  return Address(Res, LTy, Align);
3064 }
3065 
3066 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3067  QualType Ty) const {
3068  // Assume that va_list type is correct; should be pointer to LLVM type:
3069  // struct {
3070  // i32 gp_offset;
3071  // i32 fp_offset;
3072  // i8* overflow_arg_area;
3073  // i8* reg_save_area;
3074  // };
3075  unsigned neededInt, neededSSE;
3076 
3077  Ty = getContext().getCanonicalType(Ty);
3078  ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3079  /*isNamedArg*/false);
3080 
3081  // Empty records are ignored for parameter passing purposes.
3082  if (AI.isIgnore())
3083  return CGF.CreateMemTemp(Ty);
3084 
3085  // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3086  // in the registers. If not go to step 7.
3087  if (!neededInt && !neededSSE)
3088  return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3089 
3090  // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3091  // general purpose registers needed to pass type and num_fp to hold
3092  // the number of floating point registers needed.
3093 
3094  // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3095  // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3096  // l->fp_offset > 304 - num_fp * 16 go to step 7.
3097  //
3098  // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3099  // register save space).
3100 
3101  llvm::Value *InRegs = nullptr;
3102  Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3103  llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3104  if (neededInt) {
3105  gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
3106  gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3107  InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3108  InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3109  }
3110 
3111  if (neededSSE) {
3112  fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
3113  fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3114  llvm::Value *FitsInFP =
3115  llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3116  FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3117  InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3118  }
3119 
3120  llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3121  llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3122  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3123  CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3124 
3125  // Emit code to load the value if it was passed in registers.
3126 
3127  CGF.EmitBlock(InRegBlock);
3128 
3129  // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3130  // an offset of l->gp_offset and/or l->fp_offset. This may require
3131  // copying to a temporary location in case the parameter is passed
3132  // in different register classes or requires an alignment greater
3133  // than 8 for general purpose registers and 16 for XMM registers.
3134  //
3135  // FIXME: This really results in shameful code when we end up needing to
3136  // collect arguments from different places; often what should result in a
3137  // simple assembling of a structure from scattered addresses has many more
3138  // loads than necessary. Can we clean this up?
3139  llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3140  llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3141  CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
3142 
3143  Address RegAddr = Address::invalid();
3144  if (neededInt && neededSSE) {
3145  // FIXME: Cleanup.
3146  assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3147  llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
3148  Address Tmp = CGF.CreateMemTemp(Ty);
3149  Tmp = Tmp.withElementType(ST);
3150  assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3151  llvm::Type *TyLo = ST->getElementType(0);
3152  llvm::Type *TyHi = ST->getElementType(1);
3153  assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3154  "Unexpected ABI info for mixed regs");
3155  llvm::Value *GPAddr =
3156  CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
3157  llvm::Value *FPAddr =
3158  CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
3159  llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3160  llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3161 
3162  // Copy the first element.
3163  // FIXME: Our choice of alignment here and below is probably pessimistic.
3164  llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3165  TyLo, RegLoAddr,
3166  CharUnits::fromQuantity(getDataLayout().getABITypeAlign(TyLo)));
3167  CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3168 
3169  // Copy the second element.
3170  V = CGF.Builder.CreateAlignedLoad(
3171  TyHi, RegHiAddr,
3172  CharUnits::fromQuantity(getDataLayout().getABITypeAlign(TyHi)));
3173  CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3174 
3175  RegAddr = Tmp.withElementType(LTy);
3176  } else if (neededInt) {
3177  RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
3178  LTy, CharUnits::fromQuantity(8));
3179 
3180  // Copy to a temporary if necessary to ensure the appropriate alignment.
3181  auto TInfo = getContext().getTypeInfoInChars(Ty);
3182  uint64_t TySize = TInfo.Width.getQuantity();
3183  CharUnits TyAlign = TInfo.Align;
3184 
3185  // Copy into a temporary if the type is more aligned than the
3186  // register save area.
3187  if (TyAlign.getQuantity() > 8) {
3188  Address Tmp = CGF.CreateMemTemp(Ty);
3189  CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3190  RegAddr = Tmp;
3191  }
3192 
3193  } else if (neededSSE == 1) {
3194  RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
3195  LTy, CharUnits::fromQuantity(16));
3196  } else {
3197  assert(neededSSE == 2 && "Invalid number of needed registers!");
3198  // SSE registers are spaced 16 bytes apart in the register save
3199  // area, we need to collect the two eightbytes together.
3200  // The ABI isn't explicit about this, but it seems reasonable
3201  // to assume that the slots are 16-byte aligned, since the stack is
3202  // naturally 16-byte aligned and the prologue is expected to store
3203  // all the SSE registers to the RSA.
3204  Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
3205  fp_offset),
3206  CGF.Int8Ty, CharUnits::fromQuantity(16));
3207  Address RegAddrHi =
3208  CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3210  llvm::Type *ST = AI.canHaveCoerceToType()
3211  ? AI.getCoerceToType()
3212  : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
3213  llvm::Value *V;
3214  Address Tmp = CGF.CreateMemTemp(Ty);
3215  Tmp = Tmp.withElementType(ST);
3216  V = CGF.Builder.CreateLoad(
3217  RegAddrLo.withElementType(ST->getStructElementType(0)));
3218  CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3219  V = CGF.Builder.CreateLoad(
3220  RegAddrHi.withElementType(ST->getStructElementType(1)));
3221  CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3222 
3223  RegAddr = Tmp.withElementType(LTy);
3224  }
3225 
3226  // AMD64-ABI 3.5.7p5: Step 5. Set:
3227  // l->gp_offset = l->gp_offset + num_gp * 8
3228  // l->fp_offset = l->fp_offset + num_fp * 16.
3229  if (neededInt) {
3230  llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3231  CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3232  gp_offset_p);
3233  }
3234  if (neededSSE) {
3235  llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
3236  CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3237  fp_offset_p);
3238  }
3239  CGF.EmitBranch(ContBlock);
3240 
3241  // Emit code to load the value if it was passed in memory.
3242 
3243  CGF.EmitBlock(InMemBlock);
3244  Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3245 
3246  // Return the appropriate result.
3247 
3248  CGF.EmitBlock(ContBlock);
3249  Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3250  "vaarg.addr");
3251  return ResAddr;
3252 }
3253 
3254 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3255  QualType Ty) const {
3256  // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3257  // not 1, 2, 4, or 8 bytes, must be passed by reference."
3258  uint64_t Width = getContext().getTypeSize(Ty);
3259  bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3260 
3261  return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
3262  CGF.getContext().getTypeInfoInChars(Ty),
3264  /*allowHigherAlign*/ false);
3265 }
3266 
3267 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
3268  QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
3269  const Type *Base = nullptr;
3270  uint64_t NumElts = 0;
3271 
3272  if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3273  isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3274  FreeSSERegs -= NumElts;
3275  return getDirectX86Hva();
3276  }
3277  return current;
3278 }
3279 
3280 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3281  bool IsReturnType, bool IsVectorCall,
3282  bool IsRegCall) const {
3283 
3284  if (Ty->isVoidType())
3285  return ABIArgInfo::getIgnore();
3286 
3287  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3288  Ty = EnumTy->getDecl()->getIntegerType();
3289 
3290  TypeInfo Info = getContext().getTypeInfo(Ty);
3291  uint64_t Width = Info.Width;
3292  CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
3293 
3294  const RecordType *RT = Ty->getAs<RecordType>();
3295  if (RT) {
3296  if (!IsReturnType) {
3297  if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
3298  return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3299  }
3300 
3301  if (RT->getDecl()->hasFlexibleArrayMember())
3302  return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3303 
3304  }
3305 
3306  const Type *Base = nullptr;
3307  uint64_t NumElts = 0;
3308  // vectorcall adds the concept of a homogenous vector aggregate, similar to
3309  // other targets.
3310  if ((IsVectorCall || IsRegCall) &&
3311  isHomogeneousAggregate(Ty, Base, NumElts)) {
3312  if (IsRegCall) {
3313  if (FreeSSERegs >= NumElts) {
3314  FreeSSERegs -= NumElts;
3315  if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3316  return ABIArgInfo::getDirect();
3317  return ABIArgInfo::getExpand();
3318  }
3319  return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3320  } else if (IsVectorCall) {
3321  if (FreeSSERegs >= NumElts &&
3322  (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3323  FreeSSERegs -= NumElts;
3324  return ABIArgInfo::getDirect();
3325  } else if (IsReturnType) {
3326  return ABIArgInfo::getExpand();
3327  } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3328  // HVAs are delayed and reclassified in the 2nd step.
3329  return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3330  }
3331  }
3332  }
3333 
3334  if (Ty->isMemberPointerType()) {
3335  // If the member pointer is represented by an LLVM int or ptr, pass it
3336  // directly.
3337  llvm::Type *LLTy = CGT.ConvertType(Ty);
3338  if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3339  return ABIArgInfo::getDirect();
3340  }
3341 
3342  if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
3343  // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3344  // not 1, 2, 4, or 8 bytes, must be passed by reference."
3345  if (Width > 64 || !llvm::isPowerOf2_64(Width))
3346  return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3347 
3348  // Otherwise, coerce it to a small integer.
3349  return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
3350  }
3351 
3352  if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3353  switch (BT->getKind()) {
3354  case BuiltinType::Bool:
3355  // Bool type is always extended to the ABI, other builtin types are not
3356  // extended.
3357  return ABIArgInfo::getExtend(Ty);
3358 
3359  case BuiltinType::LongDouble:
3360  // Mingw64 GCC uses the old 80 bit extended precision floating point
3361  // unit. It passes them indirectly through memory.
3362  if (IsMingw64) {
3363  const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3364  if (LDF == &llvm::APFloat::x87DoubleExtended())
3365  return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3366  }
3367  break;
3368 
3369  case BuiltinType::Int128:
3370  case BuiltinType::UInt128:
3371  // If it's a parameter type, the normal ABI rule is that arguments larger
3372  // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
3373  // even though it isn't particularly efficient.
3374  if (!IsReturnType)
3375  return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3376 
3377  // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
3378  // Clang matches them for compatibility.
3379  return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
3380  llvm::Type::getInt64Ty(getVMContext()), 2));
3381 
3382  default:
3383  break;
3384  }
3385  }
3386 
3387  if (Ty->isBitIntType()) {
3388  // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3389  // not 1, 2, 4, or 8 bytes, must be passed by reference."
3390  // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
3391  // or 8 bytes anyway as long is it fits in them, so we don't have to check
3392  // the power of 2.
3393  if (Width <= 64)
3394  return ABIArgInfo::getDirect();
3395  return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3396  }
3397 
3398  return ABIArgInfo::getDirect();
3399 }
3400 
3401 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3402  ASTContext &Context = getContext();
3403  if (doOpenCLClassification(FI, Context))
3404  return;
3405 
3406  const unsigned CC = FI.getCallingConvention();
3407  bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
3408  bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
3409 
3410  // If __attribute__((sysv_abi)) is in use, use the SysV argument
3411  // classification rules.
3412  if (CC == llvm::CallingConv::X86_64_SysV) {
3413  X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
3414  SysVABIInfo.computeInfo(FI);
3415  return;
3416  }
3417 
3418  unsigned FreeSSERegs = 0;
3419  if (IsVectorCall) {
3420  // We can use up to 4 SSE return registers with vectorcall.
3421  FreeSSERegs = 4;
3422  } else if (IsRegCall) {
3423  // RegCall gives us 16 SSE registers.
3424  FreeSSERegs = 16;
3425  }
3426 
3427  if (!getCXXABI().classifyReturnType(FI))
3428  FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3429  IsVectorCall, IsRegCall);
3430 
3431  if (IsVectorCall) {
3432  // We can use up to 6 SSE register parameters with vectorcall.
3433  FreeSSERegs = 6;
3434  } else if (IsRegCall) {
3435  // RegCall gives us 16 SSE registers, we can reuse the return registers.
3436  FreeSSERegs = 16;
3437  }
3438 
3439  unsigned ArgNum = 0;
3440  unsigned ZeroSSERegs = 0;
3441  for (auto &I : FI.arguments()) {
3442  // Vectorcall in x64 only permits the first 6 arguments to be passed as
3443  // XMM/YMM registers. After the sixth argument, pretend no vector
3444  // registers are left.
3445  unsigned *MaybeFreeSSERegs =
3446  (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
3447  I.info =
3448  classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
3449  ++ArgNum;
3450  }
3451 
3452  if (IsVectorCall) {
3453  // For vectorcall, assign aggregate HVAs to any free vector registers in a
3454  // second pass.
3455  for (auto &I : FI.arguments())
3456  I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
3457  }
3458 }
3459 
3460 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3461  QualType Ty) const {
3462  // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3463  // not 1, 2, 4, or 8 bytes, must be passed by reference."
3464  uint64_t Width = getContext().getTypeSize(Ty);
3465  bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3466 
3467  return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
3468  CGF.getContext().getTypeInfoInChars(Ty),
3470  /*allowHigherAlign*/ false);
3471 }
3472 
3473 std::unique_ptr<TargetCodeGenInfo> CodeGen::createX86_32TargetCodeGenInfo(
3474  CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
3475  unsigned NumRegisterParameters, bool SoftFloatABI) {
3476  bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(
3477  CGM.getTriple(), CGM.getCodeGenOpts());
3478  return std::make_unique<X86_32TargetCodeGenInfo>(
3479  CGM.getTypes(), DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
3480  NumRegisterParameters, SoftFloatABI);
3481 }
3482 
3483 std::unique_ptr<TargetCodeGenInfo> CodeGen::createWinX86_32TargetCodeGenInfo(
3484  CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
3485  unsigned NumRegisterParameters) {
3486  bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(
3487  CGM.getTriple(), CGM.getCodeGenOpts());
3488  return std::make_unique<WinX86_32TargetCodeGenInfo>(
3489  CGM.getTypes(), DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
3490  NumRegisterParameters);
3491 }
3492 
3493 std::unique_ptr<TargetCodeGenInfo>
3495  X86AVXABILevel AVXLevel) {
3496  return std::make_unique<X86_64TargetCodeGenInfo>(CGM.getTypes(), AVXLevel);
3497 }
3498 
3499 std::unique_ptr<TargetCodeGenInfo>
3501  X86AVXABILevel AVXLevel) {
3502  return std::make_unique<WinX86_64TargetCodeGenInfo>(CGM.getTypes(), AVXLevel);
3503 }
#define V(N, I)
Definition: ASTContext.h:3299
static bool checkAVX512ParamFeature(DiagnosticsEngine &Diag, SourceLocation CallLoc, const llvm::StringMap< bool > &CallerMap, const llvm::StringMap< bool > &CalleeMap, QualType Ty, bool IsArgument)
Definition: X86.cpp:1568
static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context)
Definition: X86.cpp:387
static llvm::Type * getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset, const llvm::DataLayout &TD)
getFPTypeAtOffset - Return a floating point type at the specified offset.
Definition: X86.cpp:2422
static llvm::Type * GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, const llvm::DataLayout &TD)
GetX86_64ByValArgumentPair - Given a high and low type that can ideally be used as elements of a two ...
Definition: X86.cpp:2580
static void rewriteInputConstraintReferences(unsigned FirstIn, unsigned NumNewOuts, std::string &AsmString)
Rewrite input constraint references after adding some output constraints.
Definition: X86.cpp:262
static void initFeatureMaps(const ASTContext &Ctx, llvm::StringMap< bool > &CallerMap, const FunctionDecl *Caller, llvm::StringMap< bool > &CalleeMap, const FunctionDecl *Callee)
Definition: X86.cpp:1532
static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx, SourceLocation CallLoc, const llvm::StringMap< bool > &CallerMap, const llvm::StringMap< bool > &CalleeMap, QualType Ty, bool IsArgument)
Definition: X86.cpp:1586
static bool checkAVXParamFeature(DiagnosticsEngine &Diag, SourceLocation CallLoc, const llvm::StringMap< bool > &CallerMap, const llvm::StringMap< bool > &CalleeMap, QualType Ty, StringRef Feature, bool IsArgument)
Definition: X86.cpp:1546
static ABIArgInfo classifyOpenCL(QualType Ty, ASTContext &Context)
Definition: X86.cpp:910
static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, uint64_t &Size)
Definition: X86.cpp:423
static bool doOpenCLClassification(CGFunctionInfo &FI, ASTContext &Context)
Definition: X86.cpp:927
static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, uint64_t &Size)
Definition: X86.cpp:403
static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, unsigned EndBit, ASTContext &Context)
BitsContainNoUserData - Return true if the specified [start,end) bit range is known to either be off ...
Definition: X86.cpp:2344
static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, Address VAListAddr, QualType Ty)
Definition: X86.cpp:3029
static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM)
Definition: X86.cpp:1159
static bool isArgInAlloca(const ABIArgInfo &Info)
Definition: X86.cpp:1044
unsigned Offset
Definition: Format.cpp:2978
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
LineState State
__DEVICE__ int min(int __a, int __b)
__DEVICE__ int max(int __a, int __b)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2782
const LangOptions & getLangOpts() const
Definition: ASTContext.h:778
TypeInfoChars getTypeInfoInChars(const Type *T) const
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2355
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:760
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getRequiredAlignment() const
Definition: RecordLayout.h:311
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
A fixed int type of a specified bitwidth.
Definition: Type.h:7254
This class is used for builtin types like 'int'.
Definition: Type.h:2989
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
base_class_range bases()
Definition: DeclCXX.h:619
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
bool isMultipleOf(CharUnits N) const
Test whether this is a multiple of the other value.
Definition: CharUnits.h:143
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition: CharUnits.h:201
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
static ABIArgInfo getInAlloca(unsigned FieldIndex, bool Indirect=false)
static ABIArgInfo getIgnore()
static ABIArgInfo getExpand()
void setIndirectAlign(CharUnits IA)
static ABIArgInfo getExtendInReg(QualType Ty, llvm::Type *T=nullptr)
static ABIArgInfo getExpandWithPadding(bool PaddingInReg, llvm::Type *Padding)
static ABIArgInfo getIndirect(CharUnits Alignment, bool ByVal=true, bool Realign=false, llvm::Type *Padding=nullptr)
static ABIArgInfo getDirect(llvm::Type *T=nullptr, unsigned Offset=0, llvm::Type *Padding=nullptr, bool CanBeFlattened=true, unsigned Align=0)
@ Extend
Extend - Valid only for integer argument types.
@ Ignore
Ignore - Ignore the argument (treat as void).
@ IndirectAliased
IndirectAliased - Similar to Indirect, but the pointer may be to an object that is otherwise referenc...
@ Expand
Expand - Only valid for aggregate argument types.
@ InAlloca
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
@ CoerceAndExpand
CoerceAndExpand - Only valid for aggregate argument types.
@ Direct
Direct - Pass the argument directly using the normal converted LLVM type, or by coercing to another s...
static ABIArgInfo getExtend(QualType Ty, llvm::Type *T=nullptr)
llvm::Type * getCoerceToType() const
static ABIArgInfo getDirectInReg(llvm::Type *T=nullptr)
ABIInfo - Target specific hooks for defining how a type should be passed or returned from functions.
Definition: ABIInfo.h:45
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:111
static Address invalid()
Definition: Address.h:153
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:241
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition: CGBuilder.h:305
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:128
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:292
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:136
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:219
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:108
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:364
RecordArgABI
Specify how one should pass an argument of a record type.
Definition: CGCXXABI.h:150
@ RAA_Indirect
Pass it as a pointer to temporary memory.
Definition: CGCXXABI.h:161
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
Definition: CGCXXABI.h:158
CGFunctionInfo - Class to encapsulate the information about a function definition.
unsigned getCallingConvention() const
getCallingConvention - Return the user specified calling convention, which has been translated into a...
const_arg_iterator arg_begin() const
CanQualType getReturnType() const
MutableArrayRef< ArgInfo > arguments()
const_arg_iterator arg_end() const
void setArgStruct(llvm::StructType *Ty, CharUnits Align)
unsigned getMaxVectorWidth() const
Return the maximum vector width in the arguments.
unsigned getNumRequiredArgs() const
void setMaxVectorWidth(unsigned Width)
Set the maximum vector width in the arguments.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:257
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
llvm::LLVMContext & getLLVMContext()
llvm::Type * ConvertTypeForMem(QualType T)
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition: CGStmt.cpp:598
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition: CGExpr.cpp:147
const CGFunctionInfo * CurFnInfo
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:578
This class organizes the cross-function state that is used while generating LLVM code.
const TargetInfo & getTarget() const
const llvm::Triple & getTriple() const
DiagnosticsEngine & getDiags() const
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
Definition: CodeGenTypes.h:54
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
LValue - This represents an lvalue references.
Definition: CGValue.h:181
Address getAddress() const
Definition: CGValue.h:370
QualType getType() const
Definition: CGValue.h:294
void setAddress(Address address)
Definition: CGValue.h:372
A class for recording the number of arguments that a function signature requires.
Target specific hooks for defining how a type should be passed or returned from functions with one of...
Definition: ABIInfo.h:128
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
Definition: TargetInfo.h:46
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
Definition: TargetInfo.h:75
static std::string qualifyWindowsLibrary(StringRef Lib)
Definition: X86.cpp:1653
virtual bool isNoProtoCallVariadic(const CodeGen::CallArgList &args, const FunctionNoProtoType *fnType) const
Determine whether a call to an unprototyped functions under the given calling convention should use t...
Definition: TargetInfo.cpp:86
Complex values, per C99 6.2.5p11.
Definition: Type.h:3098
QualType getElementType() const
Definition: Type.h:3108
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3568
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2342
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool hasAttr() const
Definition: DeclBase.h:583
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:193
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5587
Represents a function declaration or definition.
Definition: Decl.h:1972
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3696
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2709
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4623
CallingConv getCallConv() const
Definition: Type.h:4596
@ Ver11
Attempt to be ABI-compatible with code generated by Clang 11.0.x (git 2e10b7a39b93).
@ Ver3_8
Attempt to be ABI-compatible with code generated by Clang 3.8.x (SVN r257626).
@ Ver9
Attempt to be ABI-compatible with code generated by Clang 9.0.x (SVN r351319).
A (possibly-)qualified type.
Definition: Type.h:940
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7371
QualType getCanonicalType() const
Definition: Type.h:7423
Represents a struct/union/class.
Definition: Decl.h:4171
bool hasFlexibleArrayMember() const
Definition: Decl.h:4204
field_iterator field_end() const
Definition: Decl.h:4380
field_range fields() const
Definition: Decl.h:4377
field_iterator field_begin() const
Definition: Decl.cpp:5073
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5561
RecordDecl * getDecl() const
Definition: Type.h:5571
Encodes a location in the source.
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:785
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
The base class of the type hierarchy.
Definition: Type.h:1813
bool isBlockPointerType() const
Definition: Type.h:7632
bool isVoidType() const
Definition: Type.h:7939
bool isFloat16Type() const
Definition: Type.h:7948
bool isPointerType() const
Definition: Type.h:7624
bool isReferenceType() const
Definition: Type.h:7636
bool isEnumeralType() const
Definition: Type.h:7722
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8054
bool isBitIntType() const
Definition: Type.h:7874
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7908
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:7714
bool isAnyComplexType() const
Definition: Type.h:7726
bool isMemberPointerType() const
Definition: Type.h:7672
bool isBFloat16Type() const
Definition: Type.h:7960
bool isMemberFunctionPointerType() const
Definition: Type.h:7676
bool isVectorType() const
Definition: Type.h:7730
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8160
bool isRecordType() const
Definition: Type.h:7718
bool isUnionType() const
Definition: Type.cpp:671
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:8101
QualType getType() const
Definition: Decl.h:718
Represents a GCC generic vector type.
Definition: Type.h:3981
#define UINT_MAX
Definition: limits.h:64
bool shouldPassIndirectly(CodeGenModule &CGM, ArrayRef< llvm::Type * > types, bool asReturnValue)
Should an aggregate which expands to the given type sequence be passed/returned indirectly under swif...
ABIArgInfo classifyReturnType(CodeGenModule &CGM, CanQualType type)
Classify the rules for how to return a particular type.
ABIArgInfo classifyArgumentType(CodeGenModule &CGM, CanQualType type)
Classify the rules for how to pass a particular type.
CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, CGCXXABI &CXXABI)
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
Definition: X86.cpp:3494
bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, const ABIInfo &Info)
Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType ValueTy, bool IsIndirect, TypeInfoChars ValueInfo, CharUnits SlotSizeAndAlign, bool AllowHigherAlign, bool ForceRightAdjust=false)
Emit va_arg for a platform using the common void* representation, where arguments are simply emitted ...
std::unique_ptr< TargetCodeGenInfo > createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters)
Definition: X86.cpp:3483
bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty)
Address emitMergePHI(CodeGenFunction &CGF, Address Addr1, llvm::BasicBlock *Block1, Address Addr2, llvm::BasicBlock *Block2, const llvm::Twine &Name="")
X86AVXABILevel
The AVX ABI level for X86 targets.
Definition: TargetInfo.h:545
bool isEmptyField(ASTContext &Context, const FieldDecl *FD, bool AllowArrays, bool AsIfNoUniqueAddr=false)
isEmptyField - Return true iff a the field is "empty", that is it is an unnamed bit-field or an (arra...
llvm::Value * emitRoundPointerUpToAlignment(CodeGenFunction &CGF, llvm::Value *Ptr, CharUnits Align)
bool isAggregateTypeForABI(QualType T)
const Type * isSingleElementStruct(QualType T, ASTContext &Context)
isSingleElementStruct - Determine if a structure is a "single element struct", i.e.
void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, llvm::Value *Array, llvm::Value *Value, unsigned FirstIndex, unsigned LastIndex)
Definition: ABIInfoImpl.cpp:89
QualType useFirstFieldIfTransparentUnion(QualType Ty)
Pass transparent unions as if they were the type of the first element.
std::unique_ptr< TargetCodeGenInfo > createX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI)
Definition: X86.cpp:3473
bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays, bool AsIfNoUniqueAddr=false)
isEmptyRecord - Return true iff a structure contains only empty fields.
std::unique_ptr< TargetCodeGenInfo > createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
Definition: X86.cpp:3500
bool isSIMDVectorType(ASTContext &Context, QualType Ty)
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:218
The JSON file list parser is used to communicate input to InstallAPI.
const FunctionProtoType * T
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_C
Definition: Specifiers.h:276
@ Class
The "class" keyword introduces the elaborated-type-specifier.
unsigned long uint64_t
Definition: Format.h:5433
#define false
Definition: stdbool.h:26
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
bool isAlignRequired()
Definition: ASTContext.h:164
uint64_t Width
Definition: ASTContext.h:156
unsigned Align
Definition: ASTContext.h:157