1 //===-- llvm/CodeGen/LowLevelType.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 /// \file This file implements the more header-heavy bits of the LLT class to
10 /// avoid polluting users' namespaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/LowLevelType.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/Support/raw_ostream.h"
19 using namespace llvm;
20 
21 LLT llvm::getLLTForType(Type &Ty, const DataLayout &DL) {
22   if (auto VTy = dyn_cast<VectorType>(&Ty)) {
23     auto EC = VTy->getElementCount();
24     LLT ScalarTy = getLLTForType(*VTy->getElementType(), DL);
25     if (EC.isScalar())
26       return ScalarTy;
27     return LLT::vector(EC, ScalarTy);
28   }
29 
30   if (auto PTy = dyn_cast<PointerType>(&Ty)) {
31     unsigned AddrSpace = PTy->getAddressSpace();
32     return LLT::pointer(AddrSpace, DL.getPointerSizeInBits(AddrSpace));
33   }
34 
35   if (Ty.isSized()) {
36     // Aggregates are no different from real scalars as far as GlobalISel is
37     // concerned.
38     auto SizeInBits = DL.getTypeSizeInBits(&Ty);
39     assert(SizeInBits != 0 && "invalid zero-sized type");
40     return LLT::scalar(SizeInBits);
41   }
42 
43   return LLT();
44 }
45 
46 MVT llvm::getMVTForLLT(LLT Ty) {
47   if (!Ty.isVector())
48     return MVT::getIntegerVT(Ty.getSizeInBits());
49 
50   return MVT::getVectorVT(
51       MVT::getIntegerVT(Ty.getElementType().getSizeInBits()),
52       Ty.getNumElements());
53 }
54 
55 EVT llvm::getApproximateEVTForLLT(LLT Ty, const DataLayout &DL,
56                                   LLVMContext &Ctx) {
57   if (Ty.isVector()) {
58     EVT EltVT = getApproximateEVTForLLT(Ty.getElementType(), DL, Ctx);
59     return EVT::getVectorVT(Ctx, EltVT, Ty.getElementCount());
60   }
61 
62   return EVT::getIntegerVT(Ctx, Ty.getSizeInBits());
63 }
64 
65 LLT llvm::getLLTForMVT(MVT Ty) {
66   if (!Ty.isVector())
67     return LLT::scalar(Ty.getSizeInBits());
68 
69   return LLT::scalarOrVector(Ty.getVectorElementCount(),
70                              Ty.getVectorElementType().getSizeInBits());
71 }
72 
73 const llvm::fltSemantics &llvm::getFltSemanticForLLT(LLT Ty) {
74   assert(Ty.isScalar() && "Expected a scalar type.");
75   switch (Ty.getSizeInBits()) {
76   case 16:
77     return APFloat::IEEEhalf();
78   case 32:
79     return APFloat::IEEEsingle();
80   case 64:
81     return APFloat::IEEEdouble();
82   case 128:
83     return APFloat::IEEEquad();
84   }
85   llvm_unreachable("Invalid FP type size.");
86 }
87