LLVM 23.0.0git
Intrinsics.cpp
Go to the documentation of this file.
1//===-- Intrinsics.cpp - Intrinsic Function Handling ------------*- C++ -*-===//
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// This file implements functions required for supporting intrinsic functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Intrinsics.h"
17#include "llvm/IR/Function.h"
18#include "llvm/IR/IntrinsicsAArch64.h"
19#include "llvm/IR/IntrinsicsAMDGPU.h"
20#include "llvm/IR/IntrinsicsARM.h"
21#include "llvm/IR/IntrinsicsBPF.h"
22#include "llvm/IR/IntrinsicsHexagon.h"
23#include "llvm/IR/IntrinsicsLoongArch.h"
24#include "llvm/IR/IntrinsicsMips.h"
25#include "llvm/IR/IntrinsicsNVPTX.h"
26#include "llvm/IR/IntrinsicsPowerPC.h"
27#include "llvm/IR/IntrinsicsR600.h"
28#include "llvm/IR/IntrinsicsRISCV.h"
29#include "llvm/IR/IntrinsicsS390.h"
30#include "llvm/IR/IntrinsicsSPIRV.h"
31#include "llvm/IR/IntrinsicsVE.h"
32#include "llvm/IR/IntrinsicsX86.h"
33#include "llvm/IR/IntrinsicsXCore.h"
34#include "llvm/IR/Module.h"
36#include "llvm/IR/Type.h"
39
40using namespace llvm;
41
42// Forward declaration of static functions.
43static bool isSignatureValid(FunctionType *FTy,
45 unsigned NumArgs, bool IsVarArg,
46 SmallVectorImpl<Type *> &OverloadTys,
47 raw_ostream &OS);
48
49/// Table of string intrinsic names indexed by enum value.
50#define GET_INTRINSIC_NAME_TABLE
51#include "llvm/IR/IntrinsicImpl.inc"
52
54 assert(id < num_intrinsics && "Invalid intrinsic ID!");
55 return IntrinsicNameTable[IntrinsicNameOffsetTable[id]];
56}
57
59 assert(id < num_intrinsics && "Invalid intrinsic ID!");
61 "This version of getName does not support overloading");
62 return getBaseName(id);
63}
64
65/// Returns a stable mangling for the type specified for use in the name
66/// mangling scheme used by 'any' types in intrinsic signatures. The mangling
67/// of named types is simply their name. Manglings for unnamed types consist
68/// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
69/// combined with the mangling of their component types. A vararg function
70/// type will have a suffix of 'vararg'. Since function types can contain
71/// other function types, we close a function type mangling with suffix 'f'
72/// which can't be confused with it's prefix. This ensures we don't have
73/// collisions between two unrelated function types. Otherwise, you might
74/// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
75/// The HasUnnamedType boolean is set if an unnamed type was encountered,
76/// indicating that extra care must be taken to ensure a unique name.
77static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType) {
78 std::string Result;
79 if (PointerType *PTyp = dyn_cast<PointerType>(Ty)) {
80 Result += "p" + utostr(PTyp->getAddressSpace());
81 } else if (ArrayType *ATyp = dyn_cast<ArrayType>(Ty)) {
82 Result += "a" + utostr(ATyp->getNumElements()) +
83 getMangledTypeStr(ATyp->getElementType(), HasUnnamedType);
84 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
85 if (!STyp->isLiteral()) {
86 Result += "s_";
87 if (STyp->hasName())
88 Result += STyp->getName();
89 else
90 HasUnnamedType = true;
91 } else {
92 Result += "sl_";
93 for (auto *Elem : STyp->elements())
94 Result += getMangledTypeStr(Elem, HasUnnamedType);
95 }
96 // Ensure nested structs are distinguishable.
97 Result += "s";
98 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
99 Result += "f_" + getMangledTypeStr(FT->getReturnType(), HasUnnamedType);
100 for (size_t i = 0; i < FT->getNumParams(); i++)
101 Result += getMangledTypeStr(FT->getParamType(i), HasUnnamedType);
102 if (FT->isVarArg())
103 Result += "vararg";
104 // Ensure nested function types are distinguishable.
105 Result += "f";
106 } else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
107 ElementCount EC = VTy->getElementCount();
108 if (EC.isScalable())
109 Result += "nx";
110 Result += "v" + utostr(EC.getKnownMinValue()) +
111 getMangledTypeStr(VTy->getElementType(), HasUnnamedType);
112 } else if (TargetExtType *TETy = dyn_cast<TargetExtType>(Ty)) {
113 Result += "t";
114 Result += TETy->getName();
115 for (Type *ParamTy : TETy->type_params())
116 Result += "_" + getMangledTypeStr(ParamTy, HasUnnamedType);
117 for (unsigned IntParam : TETy->int_params())
118 Result += "_" + utostr(IntParam);
119 // Ensure nested target extension types are distinguishable.
120 Result += "t";
121 } else if (Ty) {
122 switch (Ty->getTypeID()) {
123 default:
124 llvm_unreachable("Unhandled type");
125 case Type::VoidTyID:
126 Result += "isVoid";
127 break;
129 Result += "Metadata";
130 break;
131 case Type::HalfTyID:
132 Result += "f16";
133 break;
134 case Type::BFloatTyID:
135 Result += "bf16";
136 break;
137 case Type::FloatTyID:
138 Result += "f32";
139 break;
140 case Type::DoubleTyID:
141 Result += "f64";
142 break;
144 Result += "f80";
145 break;
146 case Type::FP128TyID:
147 Result += "f128";
148 break;
150 Result += "ppcf128";
151 break;
153 Result += "x86amx";
154 break;
156 Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
157 break;
158 case Type::ByteTyID:
159 Result += "b" + utostr(cast<ByteType>(Ty)->getBitWidth());
160 break;
161 }
162 }
163 return Result;
164}
165
167 ArrayRef<Type *> OverloadTys, Module *M,
168 FunctionType *FT,
169 bool EarlyModuleCheck) {
170
171 assert(Id < Intrinsic::num_intrinsics && "Invalid intrinsic ID!");
172 assert((OverloadTys.empty() || Intrinsic::isOverloaded(Id)) &&
173 "This version of getName is for overloaded intrinsics only");
174 (void)EarlyModuleCheck;
175 assert((!EarlyModuleCheck || M ||
176 !any_of(OverloadTys, llvm::IsaPred<PointerType>)) &&
177 "Intrinsic overloading on pointer types need to provide a Module");
178 bool HasUnnamedType = false;
179 std::string Result(Intrinsic::getBaseName(Id));
180 for (Type *Ty : OverloadTys)
181 Result += "." + getMangledTypeStr(Ty, HasUnnamedType);
182 if (HasUnnamedType) {
183 assert(M && "unnamed types need a module");
184 if (!FT)
185 FT = Intrinsic::getType(M->getContext(), Id, OverloadTys);
186 else
187 assert(FT == Intrinsic::getType(M->getContext(), Id, OverloadTys) &&
188 "Provided FunctionType must match arguments");
189 return M->getUniqueIntrinsicName(Result, Id, FT);
190 }
191 return Result;
192}
193
194std::string Intrinsic::getName(ID Id, ArrayRef<Type *> OverloadTys, Module *M,
195 FunctionType *FT) {
196 assert(M && "We need to have a Module");
197 return getIntrinsicNameImpl(Id, OverloadTys, M, FT, true);
198}
199
201 ArrayRef<Type *> OverloadTys) {
202 return getIntrinsicNameImpl(Id, OverloadTys, nullptr, nullptr, false);
203}
204
205/// IIT_Info - These are enumerators that describe the entries returned by the
206/// getIntrinsicInfoTableEntries function.
207///
208/// Defined in Intrinsics.td.
210#define GET_INTRINSIC_IITINFO
211#include "llvm/IR/IntrinsicImpl.inc"
212};
213
214static_assert(IIT_Done == 0, "IIT_Done expected to be 0");
215
216static void
217DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
219 using namespace Intrinsic;
220
221 auto IsScalableVector = [&]() {
222 IIT_Info NextInfo = IIT_Info(Infos[NextElt]);
223 if (NextInfo != IIT_SCALABLE_VEC)
224 return false;
225 // Eat the IIT_SCALABLE_VEC token.
226 ++NextElt;
227 return true;
228 };
229
230 IIT_Info Info = IIT_Info(Infos[NextElt++]);
231
232 switch (Info) {
233 case IIT_Done:
234 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
235 return;
236 case IIT_VARARG:
237 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
238 return;
239 case IIT_MMX:
240 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
241 return;
242 case IIT_AMX:
243 OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0));
244 return;
245 case IIT_TOKEN:
246 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
247 return;
248 case IIT_METADATA:
249 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
250 return;
251 case IIT_F16:
252 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
253 return;
254 case IIT_BF16:
255 OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));
256 return;
257 case IIT_F32:
258 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
259 return;
260 case IIT_F64:
261 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
262 return;
263 case IIT_F128:
264 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
265 return;
266 case IIT_PPCF128:
267 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PPCQuad, 0));
268 return;
269 case IIT_I1:
270 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
271 return;
272 case IIT_I2:
273 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 2));
274 return;
275 case IIT_I4:
276 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 4));
277 return;
278 case IIT_AARCH64_SVCOUNT:
279 OutputTable.push_back(IITDescriptor::get(IITDescriptor::AArch64Svcount, 0));
280 return;
281 case IIT_I8:
282 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
283 return;
284 case IIT_I16:
285 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 16));
286 return;
287 case IIT_I32:
288 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
289 return;
290 case IIT_I64:
291 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
292 return;
293 case IIT_I128:
294 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
295 return;
296 case IIT_V1:
297 OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector()));
298 DecodeIITType(NextElt, Infos, OutputTable);
299 return;
300 case IIT_V2:
301 OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector()));
302 DecodeIITType(NextElt, Infos, OutputTable);
303 return;
304 case IIT_V3:
305 OutputTable.push_back(IITDescriptor::getVector(3, IsScalableVector()));
306 DecodeIITType(NextElt, Infos, OutputTable);
307 return;
308 case IIT_V4:
309 OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector()));
310 DecodeIITType(NextElt, Infos, OutputTable);
311 return;
312 case IIT_V6:
313 OutputTable.push_back(IITDescriptor::getVector(6, IsScalableVector()));
314 DecodeIITType(NextElt, Infos, OutputTable);
315 return;
316 case IIT_V8:
317 OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector()));
318 DecodeIITType(NextElt, Infos, OutputTable);
319 return;
320 case IIT_V10:
321 OutputTable.push_back(IITDescriptor::getVector(10, IsScalableVector()));
322 DecodeIITType(NextElt, Infos, OutputTable);
323 return;
324 case IIT_V16:
325 OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector()));
326 DecodeIITType(NextElt, Infos, OutputTable);
327 return;
328 case IIT_V32:
329 OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector()));
330 DecodeIITType(NextElt, Infos, OutputTable);
331 return;
332 case IIT_V64:
333 OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector()));
334 DecodeIITType(NextElt, Infos, OutputTable);
335 return;
336 case IIT_V128:
337 OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector()));
338 DecodeIITType(NextElt, Infos, OutputTable);
339 return;
340 case IIT_V256:
341 OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector()));
342 DecodeIITType(NextElt, Infos, OutputTable);
343 return;
344 case IIT_V512:
345 OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector()));
346 DecodeIITType(NextElt, Infos, OutputTable);
347 return;
348 case IIT_V1024:
349 OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector()));
350 DecodeIITType(NextElt, Infos, OutputTable);
351 return;
352 case IIT_V2048:
353 OutputTable.push_back(IITDescriptor::getVector(2048, IsScalableVector()));
354 DecodeIITType(NextElt, Infos, OutputTable);
355 return;
356 case IIT_V4096:
357 OutputTable.push_back(IITDescriptor::getVector(4096, IsScalableVector()));
358 DecodeIITType(NextElt, Infos, OutputTable);
359 return;
360 case IIT_EXTERNREF:
361 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 10));
362 return;
363 case IIT_FUNCREF:
364 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 20));
365 return;
366 case IIT_PTR:
367 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
368 return;
369 case IIT_PTR_AS: // pointer with address space.
370 OutputTable.push_back(
371 IITDescriptor::get(IITDescriptor::Pointer, Infos[NextElt++]));
372 return;
373 case IIT_ANY: {
374 unsigned OverloadInfo = Infos[NextElt++];
375 OutputTable.push_back(
376 IITDescriptor::get(IITDescriptor::Overloaded, OverloadInfo));
377 return;
378 }
379 case IIT_MATCH: {
380 unsigned OverloadIndex = Infos[NextElt++];
381 OutputTable.push_back(
382 IITDescriptor::get(IITDescriptor::Match, OverloadIndex));
383 return;
384 }
385 case IIT_EXTEND_ARG: {
386 unsigned OverloadIndex = Infos[NextElt++];
387 OutputTable.push_back(
388 IITDescriptor::get(IITDescriptor::Extend, OverloadIndex));
389 return;
390 }
391 case IIT_TRUNC_ARG: {
392 unsigned OverloadIndex = Infos[NextElt++];
393 OutputTable.push_back(
394 IITDescriptor::get(IITDescriptor::Trunc, OverloadIndex));
395 return;
396 }
397 case IIT_ONE_NTH_ELTS_VEC_ARG: {
398 unsigned short OverloadIndex = Infos[NextElt++];
399 unsigned short N = Infos[NextElt++];
400 OutputTable.push_back(IITDescriptor::get(IITDescriptor::OneNthEltsVec,
401 /*Hi=*/N, /*Lo=*/OverloadIndex));
402 return;
403 }
404 case IIT_SAME_VEC_WIDTH_ARG: {
405 unsigned OverloadIndex = Infos[NextElt++];
406 OutputTable.push_back(
407 IITDescriptor::get(IITDescriptor::SameVecWidth, OverloadIndex));
408 // IIT_SAME_VEC_WIDTH_ARG entry is followed by the element type.
409 DecodeIITType(NextElt, Infos, OutputTable);
410 return;
411 }
412 case IIT_VEC_OF_ANYPTRS_TO_ELT: {
413 unsigned short OverloadIndex = Infos[NextElt++];
414 unsigned short RefOverloadIndex = Infos[NextElt++];
415 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt,
416 /*Hi=*/RefOverloadIndex,
417 /*Lo=*/OverloadIndex));
418 return;
419 }
420 case IIT_STRUCT: {
421 unsigned StructElts = Infos[NextElt++] + 2;
422
423 OutputTable.push_back(
424 IITDescriptor::get(IITDescriptor::Struct, StructElts));
425
426 for (unsigned i = 0; i != StructElts; ++i)
427 DecodeIITType(NextElt, Infos, OutputTable);
428 return;
429 }
430 case IIT_SUBDIVIDE2_ARG: {
431 unsigned OverloadIndex = Infos[NextElt++];
432 OutputTable.push_back(
433 IITDescriptor::get(IITDescriptor::Subdivide2, OverloadIndex));
434 return;
435 }
436 case IIT_SUBDIVIDE4_ARG: {
437 unsigned OverloadIndex = Infos[NextElt++];
438 OutputTable.push_back(
439 IITDescriptor::get(IITDescriptor::Subdivide4, OverloadIndex));
440 return;
441 }
442 case IIT_VEC_ELEMENT: {
443 unsigned OverloadIndex = Infos[NextElt++];
444 OutputTable.push_back(
445 IITDescriptor::get(IITDescriptor::VecElement, OverloadIndex));
446 return;
447 }
448 case IIT_VEC_OF_BITCASTS_TO_INT: {
449 unsigned OverloadIndex = Infos[NextElt++];
450 OutputTable.push_back(
451 IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt, OverloadIndex));
452 return;
453 }
454 case IIT_SCALABLE_VEC:
455 break;
456 }
457 llvm_unreachable("unhandled");
458}
459
460#define GET_INTRINSIC_GENERATOR_GLOBAL
461#include "llvm/IR/IntrinsicImpl.inc"
462
463std::tuple<ArrayRef<Intrinsic::IITDescriptor>, unsigned, bool>
466 // Note that `FixedEncodingTy` is defined in IntrinsicImpl.inc and can be
467 // uint16_t or uint32_t based on the the value of `Use16BitFixedEncoding` in
468 // IntrinsicEmitter.cpp.
469 constexpr unsigned FixedEncodingBits = sizeof(FixedEncodingTy) * CHAR_BIT;
470 constexpr unsigned MSBPosition = FixedEncodingBits - 1;
471 // Mask with all bits 1 except the most significant bit.
472 constexpr unsigned Mask = (1U << MSBPosition) - 1;
473
474 FixedEncodingTy TableVal = IIT_Table[id - 1];
475
476 // Array to hold the inlined fixed encoding values expanded from nibbles to
477 // bytes. Its size can be be atmost FixedEncodingBits / 4 i.e., number
478 // of nibbles that can fit in `FixedEncodingTy` + 1 (the IIT_Done terminator
479 // that is not explicitly encoded). Note that if there are trailing 0 bytes
480 // in the encoding (for example, payload following one of the IIT tokens),
481 // the inlined encoding does not encode the actual size of the encoding, so
482 // we always assume its size of this maximum length possible, followed by the
483 // IIT_Done terminator token (whose value is 0).
484 unsigned char IITValues[FixedEncodingBits / 4 + 1] = {0};
485
486 ArrayRef<unsigned char> IITEntries;
487 unsigned NextElt = 0;
488 // Check to see if the intrinsic's type was inlined in the fixed encoding
489 // table.
490 if (TableVal >> MSBPosition) {
491 // This is an offset into the IIT_LongEncodingTable.
492 IITEntries = IIT_LongEncodingTable;
493
494 // Strip sentinel bit.
495 NextElt = TableVal & Mask;
496 } else {
497 // If the entry was encoded into a single word in the table itself, decode
498 // it from an array of nibbles to an array of bytes.
499 do {
500 IITValues[NextElt++] = TableVal & 0xF;
501 TableVal >>= 4;
502 } while (TableVal);
503
504 IITEntries = IITValues;
505 NextElt = 0;
506 }
507
508 // Okay, decode the table into the output vector of IITDescriptors.
509 DecodeIITType(NextElt, IITEntries, T);
510 unsigned NumArgs = 0;
511 while (IITEntries[NextElt] != IIT_Done) {
512 DecodeIITType(NextElt, IITEntries, T);
513 ++NumArgs;
514 }
515
517
518 bool IsVarArg = false;
519 if (TableRef.back().Kind == Intrinsic::IITDescriptor::VarArg) {
520 IsVarArg = true;
521 TableRef.consume_back();
522 --NumArgs;
523 }
524 return {TableRef, NumArgs, IsVarArg};
525}
526
528 ArrayRef<Type *> OverloadTys,
529 LLVMContext &Context) {
530 using namespace Intrinsic;
531
532 IITDescriptor D = Infos.consume_front();
533
534 switch (D.Kind) {
535 case IITDescriptor::Void:
536 return Type::getVoidTy(Context);
537 case IITDescriptor::MMX:
539 case IITDescriptor::AMX:
540 return Type::getX86_AMXTy(Context);
541 case IITDescriptor::Token:
542 return Type::getTokenTy(Context);
543 case IITDescriptor::Metadata:
544 return Type::getMetadataTy(Context);
545 case IITDescriptor::Half:
546 return Type::getHalfTy(Context);
547 case IITDescriptor::BFloat:
548 return Type::getBFloatTy(Context);
549 case IITDescriptor::Float:
550 return Type::getFloatTy(Context);
551 case IITDescriptor::Double:
552 return Type::getDoubleTy(Context);
553 case IITDescriptor::Quad:
554 return Type::getFP128Ty(Context);
555 case IITDescriptor::PPCQuad:
556 return Type::getPPC_FP128Ty(Context);
557 case IITDescriptor::AArch64Svcount:
558 return TargetExtType::get(Context, "aarch64.svcount");
559
560 case IITDescriptor::Integer:
561 return IntegerType::get(Context, D.IntegerWidth);
562 case IITDescriptor::Vector:
563 return VectorType::get(DecodeFixedType(Infos, OverloadTys, Context),
564 D.VectorWidth);
565 case IITDescriptor::Pointer:
566 return PointerType::get(Context, D.PointerAddressSpace);
567 case IITDescriptor::Struct: {
569 for (unsigned i = 0, e = D.StructNumElements; i != e; ++i)
570 Elts.push_back(DecodeFixedType(Infos, OverloadTys, Context));
571 return StructType::get(Context, Elts);
572 }
573 // For any overload type or partially dependent type, substitute it with the
574 // corresponding concrete type from OverloadTys. Additionally, do the same
575 // for the fully dependent type that matches an overload type.
576 case IITDescriptor::Overloaded:
577 case IITDescriptor::VecOfAnyPtrsToElt:
578 case IITDescriptor::Match:
579 return OverloadTys[D.getOverloadIndex()];
580 case IITDescriptor::Extend:
581 return OverloadTys[D.getOverloadIndex()]->getExtendedType();
582 case IITDescriptor::Trunc:
583 return OverloadTys[D.getOverloadIndex()]->getTruncatedType();
584 case IITDescriptor::Subdivide2:
585 case IITDescriptor::Subdivide4: {
586 Type *Ty = OverloadTys[D.getOverloadIndex()];
588 assert(VTy && "Expected overload type to be a Vector Type");
589 int SubDivs = D.Kind == IITDescriptor::Subdivide2 ? 1 : 2;
590 return VectorType::getSubdividedVectorType(VTy, SubDivs);
591 }
592 case IITDescriptor::OneNthEltsVec:
594 cast<VectorType>(OverloadTys[D.getOverloadIndex()]),
595 D.getVectorDivisor());
596 case IITDescriptor::SameVecWidth: {
597 Type *EltTy = DecodeFixedType(Infos, OverloadTys, Context);
598 Type *Ty = OverloadTys[D.getOverloadIndex()];
599 if (auto *VTy = dyn_cast<VectorType>(Ty))
600 return VectorType::get(EltTy, VTy->getElementCount());
601 return EltTy;
602 }
603 case IITDescriptor::VecElement: {
604 Type *Ty = OverloadTys[D.getOverloadIndex()];
605 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
606 return VTy->getElementType();
607 llvm_unreachable("Expected overload type to be a Vector Type");
608 }
609 case IITDescriptor::VecOfBitcastsToInt: {
610 Type *Ty = OverloadTys[D.getOverloadIndex()];
612 assert(VTy && "Expected overload type to be a Vector Type");
613 return VectorType::getInteger(VTy);
614 }
615 case IITDescriptor::VarArg:
616 // VarArg token should be consumed by `getIntrinsicInfoTableEntries`, so we
617 // should never see it here.
618 llvm_unreachable("IITDescriptor::VarArg not expected");
619 }
620 llvm_unreachable("unhandled");
621}
622
624 ArrayRef<Type *> OverloadTys) {
626 auto [TableRef, _, IsVarArg] = getIntrinsicInfoTableEntries(id, Table);
627
628 Type *ResultTy = DecodeFixedType(TableRef, OverloadTys, Context);
629
631 while (!TableRef.empty())
632 ArgTys.push_back(DecodeFixedType(TableRef, OverloadTys, Context));
633 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
634}
635
637#define GET_INTRINSIC_OVERLOAD_TABLE
638#include "llvm/IR/IntrinsicImpl.inc"
639}
640
642#define GET_INTRINSIC_SCALARIZABLE_TABLE
643#include "llvm/IR/IntrinsicImpl.inc"
644}
645
647#define GET_INTRINSIC_PRETTY_PRINT_TABLE
648#include "llvm/IR/IntrinsicImpl.inc"
649}
650
651/// Table of per-target intrinsic name tables.
652#define GET_INTRINSIC_TARGET_DATA
653#include "llvm/IR/IntrinsicImpl.inc"
654
656 return IID > TargetInfos[0].Count;
657}
658
659/// Looks up Name in NameTable via binary search. NameTable must be sorted
660/// and all entries must start with "llvm.". If NameTable contains an exact
661/// match for Name or a prefix of Name followed by a dot, its index in
662/// NameTable is returned. Otherwise, -1 is returned.
664 StringRef Name, StringRef Target = "") {
665 assert(Name.starts_with("llvm.") && "Unexpected intrinsic prefix");
666 assert(Name.drop_front(5).starts_with(Target) && "Unexpected target");
667
668 // Do successive binary searches of the dotted name components. For
669 // "llvm.gc.experimental.statepoint.p1i8.p1i32", we will find the range of
670 // intrinsics starting with "llvm.gc", then "llvm.gc.experimental", then
671 // "llvm.gc.experimental.statepoint", and then we will stop as the range is
672 // size 1. During the search, we can skip the prefix that we already know is
673 // identical. By using strncmp we consider names with differing suffixes to
674 // be part of the equal range.
675 size_t CmpEnd = 4; // Skip the "llvm" component.
676 if (!Target.empty())
677 CmpEnd += 1 + Target.size(); // skip the .target component.
678
679 const unsigned *Low = NameOffsetTable.begin();
680 const unsigned *High = NameOffsetTable.end();
681 const unsigned *LastLow = Low;
682 while (CmpEnd < Name.size() && High - Low > 0) {
683 size_t CmpStart = CmpEnd;
684 CmpEnd = Name.find('.', CmpStart + 1);
685 CmpEnd = CmpEnd == StringRef::npos ? Name.size() : CmpEnd;
686 auto Cmp = [CmpStart, CmpEnd](auto LHS, auto RHS) {
687 // `equal_range` requires the comparison to work with either side being an
688 // offset or the value. Detect which kind each side is to set up the
689 // compared strings.
690 const char *LHSStr;
691 if constexpr (std::is_integral_v<decltype(LHS)>)
692 LHSStr = IntrinsicNameTable.getCString(LHS);
693 else
694 LHSStr = LHS;
695
696 const char *RHSStr;
697 if constexpr (std::is_integral_v<decltype(RHS)>)
698 RHSStr = IntrinsicNameTable.getCString(RHS);
699 else
700 RHSStr = RHS;
701
702 return strncmp(LHSStr + CmpStart, RHSStr + CmpStart, CmpEnd - CmpStart) <
703 0;
704 };
705 LastLow = Low;
706 std::tie(Low, High) = std::equal_range(Low, High, Name.data(), Cmp);
707 }
708 if (High - Low > 0)
709 LastLow = Low;
710
711 if (LastLow == NameOffsetTable.end())
712 return -1;
713 StringRef NameFound = IntrinsicNameTable[*LastLow];
714 if (Name == NameFound ||
715 (Name.starts_with(NameFound) && Name[NameFound.size()] == '.'))
716 return LastLow - NameOffsetTable.begin();
717 return -1;
718}
719
720/// Find the segment of \c IntrinsicNameOffsetTable for intrinsics with the same
721/// target as \c Name, or the generic table if \c Name is not target specific.
722///
723/// Returns the relevant slice of \c IntrinsicNameOffsetTable and the target
724/// name.
725static std::pair<ArrayRef<unsigned>, StringRef>
727 assert(Name.starts_with("llvm."));
728
729 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
730 // Drop "llvm." and take the first dotted component. That will be the target
731 // if this is target specific.
732 StringRef Target = Name.drop_front(5).split('.').first;
733 auto It = partition_point(
734 Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
735 // We've either found the target or just fall back to the generic set, which
736 // is always first.
737 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
738 return {ArrayRef(&IntrinsicNameOffsetTable[1] + TI.Offset, TI.Count),
739 TI.Name};
740}
741
742/// This does the actual lookup of an intrinsic ID which matches the given
743/// function name.
745 auto [NameOffsetTable, Target] = findTargetSubtable(Name);
746 int Idx = lookupLLVMIntrinsicByName(NameOffsetTable, Name, Target);
747 if (Idx == -1)
749
750 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
751 // an index into a sub-table.
752 int Adjust = NameOffsetTable.data() - IntrinsicNameOffsetTable;
753 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
754
755 // If the intrinsic is not overloaded, require an exact match. If it is
756 // overloaded, require either exact or prefix match.
757 const auto MatchSize = IntrinsicNameTable[NameOffsetTable[Idx]].size();
758 assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
759 bool IsExactMatch = Name.size() == MatchSize;
760 return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID
762}
763
764/// This defines the "Intrinsic::getAttributes(ID id)" method.
765#define GET_INTRINSIC_ATTRIBUTES
766#include "llvm/IR/IntrinsicImpl.inc"
767
768static Function *
770 ArrayRef<Type *> OverloadTys,
771 FunctionType *FT) {
772 std::string Name = OverloadTys.empty()
773 ? Intrinsic::getName(id).str()
774 : Intrinsic::getName(id, OverloadTys, M, FT);
775 Function *F = cast<Function>(M->getOrInsertFunction(Name, FT).getCallee());
776 if (F->getFunctionType() == FT)
777 return F;
778
779 // It's possible that a declaration for this intrinsic already exists with an
780 // incorrect signature, if the signature has changed, but this particular
781 // declaration has not been auto-upgraded yet. In that case, rename the
782 // invalid declaration and insert a new one with the correct signature. The
783 // invalid declaration will get upgraded later.
784 F->setName(F->getName() + ".invalid");
785 return cast<Function>(M->getOrInsertFunction(Name, FT).getCallee());
786}
787
789 ArrayRef<Type *> OverloadTys) {
790 // There can never be multiple globals with the same name of different types,
791 // because intrinsics must be a specific type.
792 FunctionType *FT = getType(M->getContext(), id, OverloadTys);
793 return getOrInsertIntrinsicDeclarationImpl(M, id, OverloadTys, FT);
794}
795
797 ArrayRef<Type *> ArgTys) {
798 // If the intrinsic is not overloaded, use the non-overloaded version.
800 return getOrInsertDeclaration(M, id);
801
802 // Get the intrinsic signature metadata.
804 auto [TableRef, NumArgs, IsVarArg] = getIntrinsicInfoTableEntries(id, Table);
805 FunctionType *FTy = FunctionType::get(RetTy, ArgTys, IsVarArg);
806
807 // Automatically determine the overloaded types.
808 SmallVector<Type *, 4> OverloadTys;
809 [[maybe_unused]] bool IsValid = ::isSignatureValid(
810 FTy, TableRef, NumArgs, IsVarArg, OverloadTys, nulls());
811 assert(IsValid && "intrinsic signature mismatch");
812 return getOrInsertIntrinsicDeclarationImpl(M, id, OverloadTys, FTy);
813}
814
816 return M->getFunction(getName(id));
817}
818
820 ArrayRef<Type *> OverloadTys,
821 FunctionType *FT) {
822 return M->getFunction(getName(id, OverloadTys, M, FT));
823}
824
825// This defines the "Intrinsic::getIntrinsicForClangBuiltin()" method.
826#define GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN
827#include "llvm/IR/IntrinsicImpl.inc"
828
829// This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
830#define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
831#include "llvm/IR/IntrinsicImpl.inc"
832
834 switch (QID) {
835#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
836 case Intrinsic::INTRINSIC:
837#include "llvm/IR/ConstrainedOps.def"
838#undef INSTRUCTION
839 return true;
840 default:
841 return false;
842 }
843}
844
846 switch (QID) {
847#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
848 case Intrinsic::INTRINSIC: \
849 return ROUND_MODE == 1;
850#include "llvm/IR/ConstrainedOps.def"
851#undef INSTRUCTION
852 default:
853 return false;
854 }
855}
856
857// This class represents a position in the intrinsic's type signature and is
858// used to generate error messages in `matchIntrinsicType`. The printed position
859// can be of the following forms:
860//
861// return
862// return struct element 3
863// return vector element
864// return struct element 3 vector element
865// argument 3
866// argument 3 vector element
867//
868// To support deferred checks also being able to generate these error messages
869// we need to encode the position compactly so that it can be stashed into
870// DeferredIntrinsicMatchInfo below (without materializing it into a string).
871// The class below serves that purpose.
872//
873namespace {
874struct MatchPosition {
875 uint16_t IsRet : 1;
876 uint16_t Num : 15; // Argument number (when IsRet = false).
877 struct Index {
878 uint16_t IsStruct : 1; // If true, this is a struct element with element
879 // index `Num`, else its a vector element.
880 uint16_t Num : 15; // Struct element index.
881 };
882 // We expect this to be just 2 levels deep, since nested structs are not
883 // supported.
884 static constexpr unsigned INDEX_TABLE_SIZE = 2;
885 Index Indices[INDEX_TABLE_SIZE];
886 uint16_t NumIndices = 0;
887
888 void pop_index() {
889 assert(NumIndices > 0 && "cannot pop from empty indices");
890 --NumIndices;
891 }
892
893 void push_struct_element(unsigned ElementNum) {
894 assert(NumIndices < INDEX_TABLE_SIZE && "index table overflow");
895 assert(isInt<15>(ElementNum) && "Element index overflow");
896 Indices[NumIndices].IsStruct = true;
897 Indices[NumIndices++].Num = ElementNum;
898 }
899
900 void push_vector_element() {
901 assert(NumIndices < INDEX_TABLE_SIZE && "index table overflow");
902 Indices[NumIndices].IsStruct = false;
903 Indices[NumIndices++].Num = 0;
904 }
905};
906} // namespace
907
908static raw_ostream &operator<<(raw_ostream &OS, const MatchPosition &Pos) {
909 OS << "intrinsic ";
910
911 if (Pos.IsRet)
912 OS << "return";
913 else
914 OS << "argument " << Pos.Num;
915
916 for (const MatchPosition::Index &Idx :
917 ArrayRef(Pos.Indices).take_front(Pos.NumIndices)) {
918 if (Idx.IsStruct)
919 OS << " struct element " << Idx.Num;
920 else
921 OS << " vector element";
922 }
923 return OS;
924}
925
927 std::tuple<Type *, ArrayRef<Intrinsic::IITDescriptor>, MatchPosition>;
928
929static bool
931 MatchPosition Position, SmallVectorImpl<Type *> &OverloadTys,
933 bool IsDeferredCheck, raw_ostream &OS) {
934 using namespace Intrinsic;
935
936 // If we ran out of descriptors, there are too many arguments or returns.
937 if (Infos.empty()) {
938 OS << Position << " too many "
939 << (Position.IsRet ? "returns" : "arguments");
940 return true;
941 }
942
943 // Do this before slicing off the 'front' part
944 auto InfosRef = Infos;
945 auto DeferCheck = [&DeferredChecks, &InfosRef, &Position](Type *T) {
946 DeferredChecks.emplace_back(T, InfosRef, Position);
947 return false;
948 };
949
950 IITDescriptor D = Infos.consume_front();
951
952 // Print error message when the (non-dependent) type for current position is
953 // invalid.
954 auto PrintMsg = [&OS, &Position,
955 Ty](bool IsValid, const Twine &Expected,
956 std::optional<unsigned> OIdx = std::nullopt) -> bool {
957 if (IsValid)
958 return false;
959 OS << Position << " type";
960 if (OIdx)
961 OS << " (overload type " << *OIdx << ")";
962 OS << " expected " << Expected << ", but got " << *Ty;
963 return true;
964 };
965
966 // Print message when an overload type is invalid as a result of its use in
967 // current dependent type. DependentQualifier describes the "function" applied
968 // to the overload type to get the dependent type.
969 auto PrintMsgInvalidOverloadTy =
970 [&OS, &Position, &OverloadTys](const Twine &DependentQualifier,
971 const Twine &Expected,
972 unsigned OIdx) -> bool {
973 OS << Position << " is " << DependentQualifier << " overload type " << OIdx
974 << ", so overload type " << OIdx << " expected " << Expected
975 << ", but got " << *OverloadTys[OIdx];
976 return true;
977 };
978
979 // Print message when a dependent type is invalid.
980 auto PrintMsgInvalidDepType =
981 [&OS, &Position, &OverloadTys,
982 Ty](bool IsValid, const Twine &DependentQualifier, const Twine &Expected,
983 unsigned OIdx) -> bool {
984 if (IsValid)
985 return false;
986 bool IsMatching = DependentQualifier.isSingleStringRef() &&
987 DependentQualifier.getSingleStringRef() == "matching";
988 OS << Position << " type (" << DependentQualifier << " overload type "
989 << OIdx << ") expected " << Expected;
990 if (!IsMatching)
991 OS << " (overload type " << OIdx << " is " << *OverloadTys[OIdx] << ")";
992 OS << ", but got " << *Ty;
993 return true;
994 };
995
996 switch (D.Kind) {
997 case IITDescriptor::Void:
998 assert(Position.IsRet && Position.NumIndices == 0 &&
999 "void descriptor expected only for return type");
1000 return PrintMsg(Ty->isVoidTy(), "void");
1001 case IITDescriptor::MMX: {
1003 return PrintMsg(VT && VT->getNumElements() == 1 &&
1004 VT->getElementType()->isIntegerTy(64),
1005 "x86_mmx (<1 x i64>)");
1006 }
1007 case IITDescriptor::AMX:
1008 return PrintMsg(Ty->isX86_AMXTy(), "x86_amx");
1009 case IITDescriptor::Token:
1010 return PrintMsg(Ty->isTokenTy(), "token");
1011 case IITDescriptor::Metadata:
1012 return PrintMsg(Ty->isMetadataTy(), "metadata");
1013 case IITDescriptor::Half:
1014 return PrintMsg(Ty->isHalfTy(), "half");
1015 case IITDescriptor::BFloat:
1016 return PrintMsg(Ty->isBFloatTy(), "bfloat");
1017 case IITDescriptor::Float:
1018 return PrintMsg(Ty->isFloatTy(), "float");
1019 case IITDescriptor::Double:
1020 return PrintMsg(Ty->isDoubleTy(), "double");
1021 case IITDescriptor::Quad:
1022 return PrintMsg(Ty->isFP128Ty(), "fp128");
1023 case IITDescriptor::PPCQuad:
1024 return PrintMsg(Ty->isPPC_FP128Ty(), "ppc_fp128");
1025 case IITDescriptor::Integer:
1026 return PrintMsg(Ty->isIntegerTy(D.IntegerWidth),
1027 "i" + Twine(D.IntegerWidth));
1028 case IITDescriptor::AArch64Svcount:
1029 return PrintMsg(isa<TargetExtType>(Ty) &&
1030 cast<TargetExtType>(Ty)->getName() == "aarch64.svcount",
1031 "aarch64.svcount");
1032 case IITDescriptor::Vector: {
1034 StringRef Scalable = D.VectorWidth.isScalable() ? "vscale " : "";
1035 bool HasError =
1036 PrintMsg(VT && VT->getElementCount() == D.VectorWidth,
1037 Twine(Scalable) + "vector with " +
1038 Twine(D.VectorWidth.getKnownMinValue()) + " elements");
1039 if (HasError)
1040 return true;
1041 Position.push_vector_element();
1042 return matchIntrinsicType(VT->getElementType(), Infos, Position,
1043 OverloadTys, DeferredChecks, IsDeferredCheck, OS);
1044 }
1045 case IITDescriptor::Pointer: {
1047 unsigned AS = D.PointerAddressSpace;
1048 bool IsValid = PT && PT->getAddressSpace() == AS;
1049 if (AS == 0)
1050 return PrintMsg(IsValid, "ptr");
1051 return PrintMsg(IsValid, "ptr addrspace(" + Twine(AS) + ")");
1052 }
1053
1054 case IITDescriptor::Struct: {
1056 unsigned EC = D.StructNumElements;
1057 bool HasError = PrintMsg(
1058 ST && ST->isLiteral() && !ST->isPacked() && ST->getNumElements() == EC,
1059 "literal non-packed struct with " + Twine(EC) + " elements");
1060 if (HasError)
1061 return true;
1062
1063 for (const auto &[Idx, ETy] : llvm::enumerate(ST->elements())) {
1064 Position.push_struct_element(Idx);
1065 if (matchIntrinsicType(ETy, Infos, Position, OverloadTys, DeferredChecks,
1066 IsDeferredCheck, OS))
1067 return true;
1068 Position.pop_index();
1069 }
1070 return false;
1071 }
1072
1073 case IITDescriptor::Overloaded: {
1074 unsigned OIdx = D.getOverloadIndex();
1075 assert(OIdx == OverloadTys.size() && !IsDeferredCheck &&
1076 "Table consistency error");
1077 OverloadTys.push_back(Ty);
1078
1079 switch (D.getOverloadKind()) {
1080 case IITDescriptor::AK_Any:
1081 return false; // Success
1082 case IITDescriptor::AK_AnyInteger:
1083 return PrintMsg(Ty->isIntOrIntVectorTy(), "any integer or integer vector",
1084 OIdx);
1085 case IITDescriptor::AK_AnyFloat:
1086 return PrintMsg(Ty->isFPOrFPVectorTy(), "any fp or fp vector", OIdx);
1087 case IITDescriptor::AK_AnyVector:
1088 return PrintMsg(isa<VectorType>(Ty), "any vector type", OIdx);
1089 case IITDescriptor::AK_AnyPointer:
1090 return PrintMsg(isa<PointerType>(Ty), "any pointer type", OIdx);
1091 }
1092 llvm_unreachable("all argument kinds not covered");
1093 }
1094
1095 case IITDescriptor::Match: {
1096 unsigned OIdx = D.getOverloadIndex();
1097 if (OIdx >= OverloadTys.size())
1098 return IsDeferredCheck || DeferCheck(Ty);
1099 return PrintMsgInvalidDepType(Ty == OverloadTys[OIdx], "matching",
1100 formatv("{}", *OverloadTys[OIdx]), OIdx);
1101 }
1102
1103 case IITDescriptor::Extend:
1104 case IITDescriptor::Trunc: {
1105 unsigned OIdx = D.getOverloadIndex();
1106 // If this is a forward reference, defer the check for later.
1107 if (OIdx >= OverloadTys.size())
1108 return IsDeferredCheck || DeferCheck(Ty);
1109
1110 Type *OTy = OverloadTys[OIdx];
1111 bool IsExtend = D.Kind == IITDescriptor::Extend;
1112 StringRef Qualifier = IsExtend ? "extended" : "truncated";
1113 if (!OTy->isIntOrIntVectorTy())
1114 return PrintMsgInvalidOverloadTy(Qualifier, "int or vector of int", OIdx);
1115
1116 Type *NewTy = IsExtend ? OTy->getExtendedType() : OTy->getTruncatedType();
1117 return PrintMsgInvalidDepType(Ty == NewTy, Qualifier, formatv("{}", *NewTy),
1118 OIdx);
1119 }
1120 case IITDescriptor::OneNthEltsVec: {
1121 unsigned OIdx = D.getOverloadIndex();
1122 unsigned Divisor = D.getVectorDivisor();
1123 // If this is a forward reference, defer the check for later.
1124 if (OIdx >= OverloadTys.size())
1125 return IsDeferredCheck || DeferCheck(Ty);
1126 Type *OTy = OverloadTys[OIdx];
1127 auto *OVecTy = dyn_cast<VectorType>(OTy);
1128 auto Qualifier = formatv("1/nth (n={}) elements vector of", Divisor);
1129 if (!OVecTy)
1130 return PrintMsgInvalidOverloadTy(Qualifier, "vector", OIdx);
1131 if (!OVecTy->getElementCount().isKnownMultipleOf(Divisor))
1132 return PrintMsgInvalidOverloadTy(
1133 Qualifier, formatv("vector with multiple of {} elements", Divisor),
1134 OIdx);
1136 return PrintMsgInvalidDepType(Expected == Ty, Qualifier,
1137 formatv("{}", *Expected), OIdx);
1138 }
1139 case IITDescriptor::SameVecWidth: {
1140 unsigned OIdx = D.getOverloadIndex();
1141 if (OIdx >= OverloadTys.size()) {
1142 // Defer check and subsequent check for the vector element type.
1143 Infos.consume_front();
1144 return IsDeferredCheck || DeferCheck(Ty);
1145 }
1146 auto *OVecTy = dyn_cast<VectorType>(OverloadTys[OIdx]);
1147 auto *ThisArgVecType = dyn_cast<VectorType>(Ty);
1148 // Both must be vectors of the same number of elements or neither.
1149 StringRef Qualifier = "same vector width of";
1150 if (OVecTy && !ThisArgVecType)
1151 return PrintMsgInvalidDepType(false, Qualifier, "vector", OIdx);
1152 if (!OVecTy && ThisArgVecType)
1153 return PrintMsgInvalidDepType(false, Qualifier, "scalar", OIdx);
1154 Type *EltTy = Ty;
1155 if (ThisArgVecType) {
1156 ElementCount Expected = OVecTy->getElementCount();
1157 if (Expected != ThisArgVecType->getElementCount())
1158 return PrintMsgInvalidDepType(
1159 false, Qualifier, formatv("vector with {} elements", Expected),
1160 OIdx);
1161 EltTy = ThisArgVecType->getElementType();
1162 Position.push_vector_element();
1163 }
1164 return matchIntrinsicType(EltTy, Infos, Position, OverloadTys,
1165 DeferredChecks, IsDeferredCheck, OS);
1166 }
1167 case IITDescriptor::VecOfAnyPtrsToElt: {
1168 unsigned RefOverloadIndex = D.getRefOverloadIndex();
1169 if (RefOverloadIndex >= OverloadTys.size()) {
1170 if (IsDeferredCheck)
1171 return true;
1172 // If forward referencing, already add the pointer-vector type and
1173 // defer the checks for later.
1174 assert(D.getOverloadIndex() == OverloadTys.size() &&
1175 "Table consistency error");
1176 OverloadTys.push_back(Ty);
1177 return DeferCheck(Ty);
1178 }
1179
1180 if (!IsDeferredCheck) {
1181 assert(D.getOverloadIndex() == OverloadTys.size() &&
1182 "Table consistency error");
1183 OverloadTys.push_back(Ty);
1184 }
1185
1186 // Verify the overloaded type "matches" the Ref type.
1187 // i.e. Ty is a vector with the same width as Ref and composed of pointers.
1188
1189 StringRef Qualifier = "vector of pointers to elements of";
1190 auto *ReferenceType = dyn_cast<VectorType>(OverloadTys[RefOverloadIndex]);
1191 if (!ReferenceType)
1192 return PrintMsgInvalidOverloadTy(Qualifier, "vector", RefOverloadIndex);
1193
1194 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1195 if (!ThisArgVecTy)
1196 return PrintMsgInvalidDepType(false, Qualifier, "vector",
1197 RefOverloadIndex);
1198
1199 auto ExpectedCount = ReferenceType->getElementCount();
1200 auto Expected =
1201 formatv("vector of pointers with {} elements", ExpectedCount);
1202 bool IsValid = ThisArgVecTy->getElementCount() == ExpectedCount &&
1203 ThisArgVecTy->getElementType()->isPointerTy();
1204 return PrintMsgInvalidDepType(IsValid, Qualifier, Expected,
1205 RefOverloadIndex);
1206 }
1207 case IITDescriptor::VecElement: {
1208 unsigned OIdx = D.getOverloadIndex();
1209 if (OIdx >= OverloadTys.size())
1210 return IsDeferredCheck || DeferCheck(Ty);
1211 StringRef Qualifier = "vector element of";
1212 auto *OVecTy = dyn_cast<VectorType>(OverloadTys[OIdx]);
1213 if (!OVecTy)
1214 return PrintMsgInvalidOverloadTy(Qualifier, "vector", OIdx);
1215 Type *Expected = OVecTy->getElementType();
1216 return PrintMsgInvalidDepType(Expected == Ty, Qualifier,
1217 formatv("{}", *Expected), OIdx);
1218 }
1219 case IITDescriptor::Subdivide2:
1220 case IITDescriptor::Subdivide4: {
1221 unsigned OIdx = D.getOverloadIndex();
1222 // If this is a forward reference, defer the check for later.
1223 if (OIdx >= OverloadTys.size())
1224 return IsDeferredCheck || DeferCheck(Ty);
1225
1226 int SubDivs = D.Kind == IITDescriptor::Subdivide2 ? 1 : 2;
1227 auto *OVecTy = dyn_cast<VectorType>(OverloadTys[OIdx]);
1228 auto Qualifier =
1229 formatv("subdivided by {} vector of", SubDivs == 1 ? 2 : 4);
1230 if (!OVecTy)
1231 return PrintMsgInvalidOverloadTy(Qualifier, "vector", OIdx);
1232
1233 // TODO: Verify that the element type of the overload type is subdivisible
1234 // by 2 or 4.
1236 return PrintMsgInvalidDepType(Expected == Ty, Qualifier,
1237 formatv("{}", *Expected), OIdx);
1238 }
1239 case IITDescriptor::VecOfBitcastsToInt: {
1240 unsigned OIdx = D.getOverloadIndex();
1241 if (OIdx >= OverloadTys.size())
1242 return IsDeferredCheck || DeferCheck(Ty);
1243 auto *OVecTy = dyn_cast<VectorType>(OverloadTys[OIdx]);
1244 StringRef Qualifier = "vector of bitcasts to int of";
1245 if (!OVecTy)
1246 return PrintMsgInvalidOverloadTy(Qualifier, "vector", OIdx);
1248 return PrintMsgInvalidDepType(Expected == Ty, Qualifier,
1249 formatv("{}", *Expected), OIdx);
1250 }
1251 case IITDescriptor::VarArg:
1252 // VarArg token should be consumed by `getIntrinsicInfoTableEntries`, so we
1253 // should never see it here.
1254 llvm_unreachable("IITDescriptor::VarArg not expected");
1255 }
1256 llvm_unreachable("unhandled");
1257}
1258
1259/// Return true if the function type \p FTy is a valid type signature for the
1260/// type constraints specified in the .td file, represented by \p Infos and
1261/// \p IsVarArg. The overloaded types for the intrinsic are pushed to the
1262/// \p OverloadTys vector.
1263///
1264/// If the type is not valid, returns false and prints an error message to
1265/// \p OS.
1268 unsigned NumArgs, bool IsVarArg,
1269 SmallVectorImpl<Type *> &OverloadTys,
1270 raw_ostream &OS) {
1272
1273 assert(!Infos.empty() && "Table consistency error");
1274
1275 MatchPosition Pos;
1276 Pos.IsRet = true;
1277 Pos.Num = 0;
1278
1279 if (matchIntrinsicType(FTy->getReturnType(), Infos, Pos, OverloadTys,
1280 DeferredChecks, false, OS))
1281 return false;
1282
1283 if (FTy->getNumParams() != NumArgs) {
1284 OS << "intrinsic has incorrect number of args. Expected " << NumArgs
1285 << ", but got " << FTy->getNumParams();
1286 return false;
1287 }
1288
1289 Pos.IsRet = false;
1290 for (const auto &[Idx, Ty] : llvm::enumerate(FTy->params())) {
1291 Pos.Num = Idx;
1292 if (matchIntrinsicType(Ty, Infos, Pos, OverloadTys, DeferredChecks, false,
1293 OS))
1294 return false;
1295 }
1296
1297 for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
1298 auto &[DefTy, DefInfos, DefPosition] = DeferredChecks[I];
1299 if (matchIntrinsicType(DefTy, DefInfos, DefPosition, OverloadTys,
1300 DeferredChecks, true, OS))
1301 return false;
1302 }
1303
1304 if (!Infos.empty()) {
1305 OS << "intrinsic has too few arguments!";
1306 return false;
1307 }
1308
1309 if (FTy->isVarArg() != IsVarArg) {
1310 if (IsVarArg)
1311 OS << "intrinsic was not defined with variable arguments!";
1312 else
1313 OS << "intrinsic was defined with variable arguments!";
1314 return false;
1315 }
1316
1317 return true;
1318}
1319
1321 using namespace Intrinsic;
1324 return !Table.empty() && Table[0].Kind == IITDescriptor::Struct;
1325}
1326
1328 SmallVectorImpl<Type *> &OverloadTys,
1329 raw_ostream &OS) {
1330 if (!ID)
1331 return false;
1332
1334 auto [TableRef, NumArgs, IsVarArg] = getIntrinsicInfoTableEntries(ID, Table);
1335
1336 return ::isSignatureValid(FT, TableRef, NumArgs, IsVarArg, OverloadTys, OS);
1337}
1338
1340 SmallVectorImpl<Type *> &OverloadTys,
1341 raw_ostream &OS) {
1342 return isSignatureValid(F->getIntrinsicID(), F->getFunctionType(),
1343 OverloadTys, OS);
1344}
1345
1347 SmallVector<Type *, 4> OverloadTys;
1348 if (!isSignatureValid(F, OverloadTys))
1349 return std::nullopt;
1350
1351 Intrinsic::ID ID = F->getIntrinsicID();
1352 StringRef Name = F->getName();
1353 std::string WantedName =
1354 Intrinsic::getName(ID, OverloadTys, F->getParent(), F->getFunctionType());
1355 if (Name == WantedName)
1356 return std::nullopt;
1357
1358 Function *NewDecl = [&] {
1359 if (auto *ExistingGV = F->getParent()->getNamedValue(WantedName)) {
1360 if (auto *ExistingF = dyn_cast<Function>(ExistingGV))
1361 if (ExistingF->getFunctionType() == F->getFunctionType())
1362 return ExistingF;
1363
1364 // The name already exists, but is not a function or has the wrong
1365 // prototype. Make place for the new one by renaming the old version.
1366 // Either this old version will be removed later on or the module is
1367 // invalid and we'll get an error.
1368 ExistingGV->setName(WantedName + ".renamed");
1369 }
1370 return Intrinsic::getOrInsertDeclaration(F->getParent(), ID, OverloadTys);
1371 }();
1372
1373 NewDecl->setCallingConv(F->getCallingConv());
1374 assert(NewDecl->getFunctionType() == F->getFunctionType() &&
1375 "Shouldn't change the signature");
1376 return NewDecl;
1377}
1378
1382
1384 {Intrinsic::vector_interleave2, Intrinsic::vector_deinterleave2},
1385 {Intrinsic::vector_interleave3, Intrinsic::vector_deinterleave3},
1386 {Intrinsic::vector_interleave4, Intrinsic::vector_deinterleave4},
1387 {Intrinsic::vector_interleave5, Intrinsic::vector_deinterleave5},
1388 {Intrinsic::vector_interleave6, Intrinsic::vector_deinterleave6},
1389 {Intrinsic::vector_interleave7, Intrinsic::vector_deinterleave7},
1390 {Intrinsic::vector_interleave8, Intrinsic::vector_deinterleave8},
1391};
1392
1394 assert(Factor >= 2 && Factor <= 8 && "Unexpected factor");
1395 return InterleaveIntrinsics[Factor - 2].Interleave;
1396}
1397
1399 assert(Factor >= 2 && Factor <= 8 && "Unexpected factor");
1400 return InterleaveIntrinsics[Factor - 2].Deinterleave;
1401}
1402
1403#define GET_INTRINSIC_PRETTY_PRINT_ARGUMENTS
1404#include "llvm/IR/IntrinsicImpl.inc"
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ArrayRef< TableEntry > TableRef
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define _
Module.h This file contains the declarations for the Module class.
static bool matchIntrinsicType(Type *Ty, ArrayRef< Intrinsic::IITDescriptor > &Infos, MatchPosition Position, SmallVectorImpl< Type * > &OverloadTys, SmallVectorImpl< DeferredIntrinsicMatchInfo > &DeferredChecks, bool IsDeferredCheck, raw_ostream &OS)
static bool isSignatureValid(FunctionType *FTy, ArrayRef< Intrinsic::IITDescriptor > &Infos, unsigned NumArgs, bool IsVarArg, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS)
Return true if the function type FTy is a valid type signature for the type constraints specified in ...
static InterleaveIntrinsic InterleaveIntrinsics[]
std::tuple< Type *, ArrayRef< Intrinsic::IITDescriptor >, MatchPosition > DeferredIntrinsicMatchInfo
static std::pair< ArrayRef< unsigned >, StringRef > findTargetSubtable(StringRef Name)
Find the segment of IntrinsicNameOffsetTable for intrinsics with the same target as Name,...
static Function * getOrInsertIntrinsicDeclarationImpl(Module *M, Intrinsic::ID id, ArrayRef< Type * > OverloadTys, FunctionType *FT)
static void DecodeIITType(unsigned &NextElt, ArrayRef< unsigned char > Infos, SmallVectorImpl< Intrinsic::IITDescriptor > &OutputTable)
static std::string getIntrinsicNameImpl(Intrinsic::ID Id, ArrayRef< Type * > OverloadTys, Module *M, FunctionType *FT, bool EarlyModuleCheck)
IIT_Info
IIT_Info - These are enumerators that describe the entries returned by the getIntrinsicInfoTableEntri...
static Type * DecodeFixedType(ArrayRef< Intrinsic::IITDescriptor > &Infos, ArrayRef< Type * > OverloadTys, LLVMContext &Context)
static int lookupLLVMIntrinsicByName(ArrayRef< unsigned > NameOffsetTable, StringRef Name, StringRef Target="")
Looks up Name in NameTable via binary search.
static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType)
Returns a stable mangling for the type specified for use in the name mangling scheme used by 'any' ty...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t High
This file contains the definitions of the enumerations and flags associated with NVVM Intrinsics,...
static StringRef getName(Value *V)
This file contains some functions that are useful when dealing with strings.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
const T & consume_front()
consume_front() - Returns the first element and drops it from ArrayRef.
Definition ArrayRef.h:156
Tagged union holding either a T or a Error.
Definition Error.h:485
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:869
Class to represent function types.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:211
const Function & getFunction() const
Definition Function.h:166
void setCallingConv(CallingConv::ID CC)
Definition Function.h:276
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:350
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:479
Class to represent target extensions types, which are generally unintrospectable from target-independ...
static LLVM_ABI TargetExtType * get(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters.
Definition Type.cpp:974
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI Type * getX86_AMXTy(LLVMContext &C)
Definition Type.cpp:293
LLVM_ABI Type * getTruncatedType() const
Given scalar/vector integer type, returns a type with elements half as wide as in the original type.
static LLVM_ABI Type * getMetadataTy(LLVMContext &C)
Definition Type.cpp:288
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:289
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
static LLVM_ABI Type * getPPC_FP128Ty(LLVMContext &C)
Definition Type.cpp:292
static LLVM_ABI Type * getFP128Ty(LLVMContext &C)
Definition Type.cpp:291
@ X86_AMXTyID
AMX vectors (8192 bits, X86 specific)
Definition Type.h:67
@ HalfTyID
16-bit floating point type
Definition Type.h:57
@ VoidTyID
type with no size
Definition Type.h:64
@ FloatTyID
32-bit floating point type
Definition Type.h:59
@ IntegerTyID
Arbitrary bit width integers.
Definition Type.h:71
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition Type.h:58
@ DoubleTyID
64-bit floating point type
Definition Type.h:60
@ X86_FP80TyID
80-bit floating point type (X87)
Definition Type.h:61
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition Type.h:63
@ MetadataTyID
Metadata.
Definition Type.h:66
@ ByteTyID
Arbitrary bit width bytes.
Definition Type.h:72
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:62
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
LLVM_ABI Type * getExtendedType() const
Given scalar/vector integer type, returns a type with elements twice as wide as in the original type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:287
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:286
static LLVM_ABI Type * getBFloatTy(LLVMContext &C)
Definition Type.cpp:285
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
Definition Type.cpp:284
static VectorType * getOneNthElementsVectorType(VectorType *VTy, unsigned Denominator)
static VectorType * getSubdividedVectorType(VectorType *VTy, int NumSubdivs)
static VectorType * getInteger(VectorType *VTy)
This static method gets a VectorType with the same number of elements as the input type,...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Intrinsic::ID getDeinterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.deinterleaveN intrinsic for factor N.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
LLVM_ABI std::optional< Function * > remangleIntrinsicFunction(Function *F)
LLVM_ABI bool hasConstrainedFPRoundingModeOperand(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics" that take r...
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI bool isConstrainedFPIntrinsic(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics".
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool hasPrettyPrintedArgs(ID id)
Returns true if the intrinsic has pretty printed immediate arguments.
LLVM_ABI std::tuple< ArrayRef< IITDescriptor >, unsigned, bool > getIntrinsicInfoTableEntries(ID id, SmallVectorImpl< IITDescriptor > &T)
Fill the IIT table descriptor for the intrinsic id into an array of IITDescriptors.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
LLVM_ABI Intrinsic::ID getInterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.interleaveN intrinsic for factor N.
LLVM_ABI bool isOverloaded(ID id)
Returns true if the intrinsic can be overloaded.
LLVM_ABI FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > OverloadTys={})
Return the function type for an intrinsic.
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
LLVM_ABI bool hasStructReturnType(ID id)
Returns true if id has a struct return type.
LLVM_ABI bool isTriviallyScalarizable(ID id)
Returns true if the intrinsic is trivially scalarizable.
LLVM_ABI bool isTargetIntrinsic(ID IID)
isTargetIntrinsic - Returns true if IID is an intrinsic specific to a certain target.
LLVM_ABI std::string getNameNoUnnamedTypes(ID Id, ArrayRef< Type * > OverloadTys)
Return the LLVM name for an intrinsic.
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:165
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2553
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
Definition STLExtras.h:2128
std::string utostr(uint64_t X, bool isNeg=false)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1745
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
LLVM_ABI raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
#define N
Intrinsic::ID Interleave
Intrinsic::ID Deinterleave