xref: /llvm-project/llvm/lib/IR/Function.cpp (revision ad5d319ee85d31ee2b1ca5c29b3a10b340513fec)
1 //===- Function.cpp - Implement the Global object classes -----------------===//
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 the Function class for the IR library.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IR/Function.h"
14 #include "SymbolTableListTraitsImpl.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/Argument.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/Constant.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/InstIterator.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/IntrinsicsAArch64.h"
35 #include "llvm/IR/IntrinsicsAMDGPU.h"
36 #include "llvm/IR/IntrinsicsARM.h"
37 #include "llvm/IR/IntrinsicsBPF.h"
38 #include "llvm/IR/IntrinsicsHexagon.h"
39 #include "llvm/IR/IntrinsicsMips.h"
40 #include "llvm/IR/IntrinsicsNVPTX.h"
41 #include "llvm/IR/IntrinsicsPowerPC.h"
42 #include "llvm/IR/IntrinsicsR600.h"
43 #include "llvm/IR/IntrinsicsRISCV.h"
44 #include "llvm/IR/IntrinsicsS390.h"
45 #include "llvm/IR/IntrinsicsWebAssembly.h"
46 #include "llvm/IR/IntrinsicsX86.h"
47 #include "llvm/IR/IntrinsicsXCore.h"
48 #include "llvm/IR/LLVMContext.h"
49 #include "llvm/IR/MDBuilder.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/SymbolTableListTraits.h"
53 #include "llvm/IR/Type.h"
54 #include "llvm/IR/Use.h"
55 #include "llvm/IR/User.h"
56 #include "llvm/IR/Value.h"
57 #include "llvm/IR/ValueSymbolTable.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/Compiler.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include <algorithm>
62 #include <cassert>
63 #include <cstddef>
64 #include <cstdint>
65 #include <cstring>
66 #include <string>
67 
68 using namespace llvm;
69 using ProfileCount = Function::ProfileCount;
70 
71 // Explicit instantiations of SymbolTableListTraits since some of the methods
72 // are not in the public header file...
73 template class llvm::SymbolTableListTraits<BasicBlock>;
74 
75 //===----------------------------------------------------------------------===//
76 // Argument Implementation
77 //===----------------------------------------------------------------------===//
78 
79 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
80     : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
81   setName(Name);
82 }
83 
84 void Argument::setParent(Function *parent) {
85   Parent = parent;
86 }
87 
88 bool Argument::hasNonNullAttr() const {
89   if (!getType()->isPointerTy()) return false;
90   if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull))
91     return true;
92   else if (getDereferenceableBytes() > 0 &&
93            !NullPointerIsDefined(getParent(),
94                                  getType()->getPointerAddressSpace()))
95     return true;
96   return false;
97 }
98 
99 bool Argument::hasByValAttr() const {
100   if (!getType()->isPointerTy()) return false;
101   return hasAttribute(Attribute::ByVal);
102 }
103 
104 bool Argument::hasSwiftSelfAttr() const {
105   return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
106 }
107 
108 bool Argument::hasSwiftErrorAttr() const {
109   return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
110 }
111 
112 bool Argument::hasInAllocaAttr() const {
113   if (!getType()->isPointerTy()) return false;
114   return hasAttribute(Attribute::InAlloca);
115 }
116 
117 bool Argument::hasPreallocatedAttr() const {
118   if (!getType()->isPointerTy())
119     return false;
120   return hasAttribute(Attribute::Preallocated);
121 }
122 
123 bool Argument::hasPassPointeeByValueAttr() const {
124   if (!getType()->isPointerTy()) return false;
125   AttributeList Attrs = getParent()->getAttributes();
126   return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
127          Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca) ||
128          Attrs.hasParamAttribute(getArgNo(), Attribute::Preallocated);
129 }
130 
131 unsigned Argument::getParamAlignment() const {
132   assert(getType()->isPointerTy() && "Only pointers have alignments");
133   return getParent()->getParamAlignment(getArgNo());
134 }
135 
136 MaybeAlign Argument::getParamAlign() const {
137   assert(getType()->isPointerTy() && "Only pointers have alignments");
138   return getParent()->getParamAlign(getArgNo());
139 }
140 
141 Type *Argument::getParamByValType() const {
142   assert(getType()->isPointerTy() && "Only pointers have byval types");
143   return getParent()->getParamByValType(getArgNo());
144 }
145 
146 uint64_t Argument::getDereferenceableBytes() const {
147   assert(getType()->isPointerTy() &&
148          "Only pointers have dereferenceable bytes");
149   return getParent()->getParamDereferenceableBytes(getArgNo());
150 }
151 
152 uint64_t Argument::getDereferenceableOrNullBytes() const {
153   assert(getType()->isPointerTy() &&
154          "Only pointers have dereferenceable bytes");
155   return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
156 }
157 
158 bool Argument::hasNestAttr() const {
159   if (!getType()->isPointerTy()) return false;
160   return hasAttribute(Attribute::Nest);
161 }
162 
163 bool Argument::hasNoAliasAttr() const {
164   if (!getType()->isPointerTy()) return false;
165   return hasAttribute(Attribute::NoAlias);
166 }
167 
168 bool Argument::hasNoCaptureAttr() const {
169   if (!getType()->isPointerTy()) return false;
170   return hasAttribute(Attribute::NoCapture);
171 }
172 
173 bool Argument::hasStructRetAttr() const {
174   if (!getType()->isPointerTy()) return false;
175   return hasAttribute(Attribute::StructRet);
176 }
177 
178 bool Argument::hasInRegAttr() const {
179   return hasAttribute(Attribute::InReg);
180 }
181 
182 bool Argument::hasReturnedAttr() const {
183   return hasAttribute(Attribute::Returned);
184 }
185 
186 bool Argument::hasZExtAttr() const {
187   return hasAttribute(Attribute::ZExt);
188 }
189 
190 bool Argument::hasSExtAttr() const {
191   return hasAttribute(Attribute::SExt);
192 }
193 
194 bool Argument::onlyReadsMemory() const {
195   AttributeList Attrs = getParent()->getAttributes();
196   return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) ||
197          Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone);
198 }
199 
200 void Argument::addAttrs(AttrBuilder &B) {
201   AttributeList AL = getParent()->getAttributes();
202   AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
203   getParent()->setAttributes(AL);
204 }
205 
206 void Argument::addAttr(Attribute::AttrKind Kind) {
207   getParent()->addParamAttr(getArgNo(), Kind);
208 }
209 
210 void Argument::addAttr(Attribute Attr) {
211   getParent()->addParamAttr(getArgNo(), Attr);
212 }
213 
214 void Argument::removeAttr(Attribute::AttrKind Kind) {
215   getParent()->removeParamAttr(getArgNo(), Kind);
216 }
217 
218 bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
219   return getParent()->hasParamAttribute(getArgNo(), Kind);
220 }
221 
222 Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
223   return getParent()->getParamAttribute(getArgNo(), Kind);
224 }
225 
226 //===----------------------------------------------------------------------===//
227 // Helper Methods in Function
228 //===----------------------------------------------------------------------===//
229 
230 LLVMContext &Function::getContext() const {
231   return getType()->getContext();
232 }
233 
234 unsigned Function::getInstructionCount() const {
235   unsigned NumInstrs = 0;
236   for (const BasicBlock &BB : BasicBlocks)
237     NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
238                                BB.instructionsWithoutDebug().end());
239   return NumInstrs;
240 }
241 
242 Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
243                            const Twine &N, Module &M) {
244   return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
245 }
246 
247 void Function::removeFromParent() {
248   getParent()->getFunctionList().remove(getIterator());
249 }
250 
251 void Function::eraseFromParent() {
252   getParent()->getFunctionList().erase(getIterator());
253 }
254 
255 //===----------------------------------------------------------------------===//
256 // Function Implementation
257 //===----------------------------------------------------------------------===//
258 
259 static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
260   // If AS == -1 and we are passed a valid module pointer we place the function
261   // in the program address space. Otherwise we default to AS0.
262   if (AddrSpace == static_cast<unsigned>(-1))
263     return M ? M->getDataLayout().getProgramAddressSpace() : 0;
264   return AddrSpace;
265 }
266 
267 Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
268                    const Twine &name, Module *ParentModule)
269     : GlobalObject(Ty, Value::FunctionVal,
270                    OperandTraits<Function>::op_begin(this), 0, Linkage, name,
271                    computeAddrSpace(AddrSpace, ParentModule)),
272       NumArgs(Ty->getNumParams()) {
273   assert(FunctionType::isValidReturnType(getReturnType()) &&
274          "invalid return type");
275   setGlobalObjectSubClassData(0);
276 
277   // We only need a symbol table for a function if the context keeps value names
278   if (!getContext().shouldDiscardValueNames())
279     SymTab = std::make_unique<ValueSymbolTable>();
280 
281   // If the function has arguments, mark them as lazily built.
282   if (Ty->getNumParams())
283     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
284 
285   if (ParentModule)
286     ParentModule->getFunctionList().push_back(this);
287 
288   HasLLVMReservedName = getName().startswith("llvm.");
289   // Ensure intrinsics have the right parameter attributes.
290   // Note, the IntID field will have been set in Value::setName if this function
291   // name is a valid intrinsic ID.
292   if (IntID)
293     setAttributes(Intrinsic::getAttributes(getContext(), IntID));
294 }
295 
296 Function::~Function() {
297   dropAllReferences();    // After this it is safe to delete instructions.
298 
299   // Delete all of the method arguments and unlink from symbol table...
300   if (Arguments)
301     clearArguments();
302 
303   // Remove the function from the on-the-side GC table.
304   clearGC();
305 }
306 
307 void Function::BuildLazyArguments() const {
308   // Create the arguments vector, all arguments start out unnamed.
309   auto *FT = getFunctionType();
310   if (NumArgs > 0) {
311     Arguments = std::allocator<Argument>().allocate(NumArgs);
312     for (unsigned i = 0, e = NumArgs; i != e; ++i) {
313       Type *ArgTy = FT->getParamType(i);
314       assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
315       new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
316     }
317   }
318 
319   // Clear the lazy arguments bit.
320   unsigned SDC = getSubclassDataFromValue();
321   SDC &= ~(1 << 0);
322   const_cast<Function*>(this)->setValueSubclassData(SDC);
323   assert(!hasLazyArguments());
324 }
325 
326 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
327   return MutableArrayRef<Argument>(Args, Count);
328 }
329 
330 bool Function::isConstrainedFPIntrinsic() const {
331   switch (getIntrinsicID()) {
332 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
333   case Intrinsic::INTRINSIC:
334 #include "llvm/IR/ConstrainedOps.def"
335     return true;
336 #undef INSTRUCTION
337   default:
338     return false;
339   }
340 }
341 
342 void Function::clearArguments() {
343   for (Argument &A : makeArgArray(Arguments, NumArgs)) {
344     A.setName("");
345     A.~Argument();
346   }
347   std::allocator<Argument>().deallocate(Arguments, NumArgs);
348   Arguments = nullptr;
349 }
350 
351 void Function::stealArgumentListFrom(Function &Src) {
352   assert(isDeclaration() && "Expected no references to current arguments");
353 
354   // Drop the current arguments, if any, and set the lazy argument bit.
355   if (!hasLazyArguments()) {
356     assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
357                         [](const Argument &A) { return A.use_empty(); }) &&
358            "Expected arguments to be unused in declaration");
359     clearArguments();
360     setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
361   }
362 
363   // Nothing to steal if Src has lazy arguments.
364   if (Src.hasLazyArguments())
365     return;
366 
367   // Steal arguments from Src, and fix the lazy argument bits.
368   assert(arg_size() == Src.arg_size());
369   Arguments = Src.Arguments;
370   Src.Arguments = nullptr;
371   for (Argument &A : makeArgArray(Arguments, NumArgs)) {
372     // FIXME: This does the work of transferNodesFromList inefficiently.
373     SmallString<128> Name;
374     if (A.hasName())
375       Name = A.getName();
376     if (!Name.empty())
377       A.setName("");
378     A.setParent(this);
379     if (!Name.empty())
380       A.setName(Name);
381   }
382 
383   setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
384   assert(!hasLazyArguments());
385   Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
386 }
387 
388 // dropAllReferences() - This function causes all the subinstructions to "let
389 // go" of all references that they are maintaining.  This allows one to
390 // 'delete' a whole class at a time, even though there may be circular
391 // references... first all references are dropped, and all use counts go to
392 // zero.  Then everything is deleted for real.  Note that no operations are
393 // valid on an object that has "dropped all references", except operator
394 // delete.
395 //
396 void Function::dropAllReferences() {
397   setIsMaterializable(false);
398 
399   for (BasicBlock &BB : *this)
400     BB.dropAllReferences();
401 
402   // Delete all basic blocks. They are now unused, except possibly by
403   // blockaddresses, but BasicBlock's destructor takes care of those.
404   while (!BasicBlocks.empty())
405     BasicBlocks.begin()->eraseFromParent();
406 
407   // Drop uses of any optional data (real or placeholder).
408   if (getNumOperands()) {
409     User::dropAllReferences();
410     setNumHungOffUseOperands(0);
411     setValueSubclassData(getSubclassDataFromValue() & ~0xe);
412   }
413 
414   // Metadata is stored in a side-table.
415   clearMetadata();
416 }
417 
418 void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) {
419   AttributeList PAL = getAttributes();
420   PAL = PAL.addAttribute(getContext(), i, Kind);
421   setAttributes(PAL);
422 }
423 
424 void Function::addAttribute(unsigned i, Attribute Attr) {
425   AttributeList PAL = getAttributes();
426   PAL = PAL.addAttribute(getContext(), i, Attr);
427   setAttributes(PAL);
428 }
429 
430 void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) {
431   AttributeList PAL = getAttributes();
432   PAL = PAL.addAttributes(getContext(), i, Attrs);
433   setAttributes(PAL);
434 }
435 
436 void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
437   AttributeList PAL = getAttributes();
438   PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
439   setAttributes(PAL);
440 }
441 
442 void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
443   AttributeList PAL = getAttributes();
444   PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
445   setAttributes(PAL);
446 }
447 
448 void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
449   AttributeList PAL = getAttributes();
450   PAL = PAL.addParamAttributes(getContext(), ArgNo, Attrs);
451   setAttributes(PAL);
452 }
453 
454 void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
455   AttributeList PAL = getAttributes();
456   PAL = PAL.removeAttribute(getContext(), i, Kind);
457   setAttributes(PAL);
458 }
459 
460 void Function::removeAttribute(unsigned i, StringRef Kind) {
461   AttributeList PAL = getAttributes();
462   PAL = PAL.removeAttribute(getContext(), i, Kind);
463   setAttributes(PAL);
464 }
465 
466 void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) {
467   AttributeList PAL = getAttributes();
468   PAL = PAL.removeAttributes(getContext(), i, Attrs);
469   setAttributes(PAL);
470 }
471 
472 void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
473   AttributeList PAL = getAttributes();
474   PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
475   setAttributes(PAL);
476 }
477 
478 void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
479   AttributeList PAL = getAttributes();
480   PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
481   setAttributes(PAL);
482 }
483 
484 void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
485   AttributeList PAL = getAttributes();
486   PAL = PAL.removeParamAttributes(getContext(), ArgNo, Attrs);
487   setAttributes(PAL);
488 }
489 
490 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
491   AttributeList PAL = getAttributes();
492   PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
493   setAttributes(PAL);
494 }
495 
496 void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
497   AttributeList PAL = getAttributes();
498   PAL = PAL.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
499   setAttributes(PAL);
500 }
501 
502 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
503   AttributeList PAL = getAttributes();
504   PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
505   setAttributes(PAL);
506 }
507 
508 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
509                                                  uint64_t Bytes) {
510   AttributeList PAL = getAttributes();
511   PAL = PAL.addDereferenceableOrNullParamAttr(getContext(), ArgNo, Bytes);
512   setAttributes(PAL);
513 }
514 
515 const std::string &Function::getGC() const {
516   assert(hasGC() && "Function has no collector");
517   return getContext().getGC(*this);
518 }
519 
520 void Function::setGC(std::string Str) {
521   setValueSubclassDataBit(14, !Str.empty());
522   getContext().setGC(*this, std::move(Str));
523 }
524 
525 void Function::clearGC() {
526   if (!hasGC())
527     return;
528   getContext().deleteGC(*this);
529   setValueSubclassDataBit(14, false);
530 }
531 
532 /// Copy all additional attributes (those not needed to create a Function) from
533 /// the Function Src to this one.
534 void Function::copyAttributesFrom(const Function *Src) {
535   GlobalObject::copyAttributesFrom(Src);
536   setCallingConv(Src->getCallingConv());
537   setAttributes(Src->getAttributes());
538   if (Src->hasGC())
539     setGC(Src->getGC());
540   else
541     clearGC();
542   if (Src->hasPersonalityFn())
543     setPersonalityFn(Src->getPersonalityFn());
544   if (Src->hasPrefixData())
545     setPrefixData(Src->getPrefixData());
546   if (Src->hasPrologueData())
547     setPrologueData(Src->getPrologueData());
548 }
549 
550 /// Table of string intrinsic names indexed by enum value.
551 static const char * const IntrinsicNameTable[] = {
552   "not_intrinsic",
553 #define GET_INTRINSIC_NAME_TABLE
554 #include "llvm/IR/IntrinsicImpl.inc"
555 #undef GET_INTRINSIC_NAME_TABLE
556 };
557 
558 /// Table of per-target intrinsic name tables.
559 #define GET_INTRINSIC_TARGET_DATA
560 #include "llvm/IR/IntrinsicImpl.inc"
561 #undef GET_INTRINSIC_TARGET_DATA
562 
563 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
564 /// target as \c Name, or the generic table if \c Name is not target specific.
565 ///
566 /// Returns the relevant slice of \c IntrinsicNameTable
567 static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
568   assert(Name.startswith("llvm."));
569 
570   ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
571   // Drop "llvm." and take the first dotted component. That will be the target
572   // if this is target specific.
573   StringRef Target = Name.drop_front(5).split('.').first;
574   auto It = partition_point(
575       Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
576   // We've either found the target or just fall back to the generic set, which
577   // is always first.
578   const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
579   return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
580 }
581 
582 /// This does the actual lookup of an intrinsic ID which
583 /// matches the given function name.
584 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
585   ArrayRef<const char *> NameTable = findTargetSubtable(Name);
586   int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
587   if (Idx == -1)
588     return Intrinsic::not_intrinsic;
589 
590   // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
591   // an index into a sub-table.
592   int Adjust = NameTable.data() - IntrinsicNameTable;
593   Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
594 
595   // If the intrinsic is not overloaded, require an exact match. If it is
596   // overloaded, require either exact or prefix match.
597   const auto MatchSize = strlen(NameTable[Idx]);
598   assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
599   bool IsExactMatch = Name.size() == MatchSize;
600   return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID
601                                                      : Intrinsic::not_intrinsic;
602 }
603 
604 void Function::recalculateIntrinsicID() {
605   StringRef Name = getName();
606   if (!Name.startswith("llvm.")) {
607     HasLLVMReservedName = false;
608     IntID = Intrinsic::not_intrinsic;
609     return;
610   }
611   HasLLVMReservedName = true;
612   IntID = lookupIntrinsicID(Name);
613 }
614 
615 /// Returns a stable mangling for the type specified for use in the name
616 /// mangling scheme used by 'any' types in intrinsic signatures.  The mangling
617 /// of named types is simply their name.  Manglings for unnamed types consist
618 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
619 /// combined with the mangling of their component types.  A vararg function
620 /// type will have a suffix of 'vararg'.  Since function types can contain
621 /// other function types, we close a function type mangling with suffix 'f'
622 /// which can't be confused with it's prefix.  This ensures we don't have
623 /// collisions between two unrelated function types. Otherwise, you might
624 /// parse ffXX as f(fXX) or f(fX)X.  (X is a placeholder for any other type.)
625 ///
626 static std::string getMangledTypeStr(Type* Ty) {
627   std::string Result;
628   if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
629     Result += "p" + utostr(PTyp->getAddressSpace()) +
630       getMangledTypeStr(PTyp->getElementType());
631   } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
632     Result += "a" + utostr(ATyp->getNumElements()) +
633       getMangledTypeStr(ATyp->getElementType());
634   } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
635     if (!STyp->isLiteral()) {
636       Result += "s_";
637       Result += STyp->getName();
638     } else {
639       Result += "sl_";
640       for (auto Elem : STyp->elements())
641         Result += getMangledTypeStr(Elem);
642     }
643     // Ensure nested structs are distinguishable.
644     Result += "s";
645   } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
646     Result += "f_" + getMangledTypeStr(FT->getReturnType());
647     for (size_t i = 0; i < FT->getNumParams(); i++)
648       Result += getMangledTypeStr(FT->getParamType(i));
649     if (FT->isVarArg())
650       Result += "vararg";
651     // Ensure nested function types are distinguishable.
652     Result += "f";
653   } else if (VectorType* VTy = dyn_cast<VectorType>(Ty)) {
654     ElementCount EC = VTy->getElementCount();
655     if (EC.Scalable)
656       Result += "nx";
657     Result += "v" + utostr(EC.Min) + getMangledTypeStr(VTy->getElementType());
658   } else if (Ty) {
659     switch (Ty->getTypeID()) {
660     default: llvm_unreachable("Unhandled type");
661     case Type::VoidTyID:      Result += "isVoid";   break;
662     case Type::MetadataTyID:  Result += "Metadata"; break;
663     case Type::HalfTyID:      Result += "f16";      break;
664     case Type::BFloatTyID:    Result += "bf16";     break;
665     case Type::FloatTyID:     Result += "f32";      break;
666     case Type::DoubleTyID:    Result += "f64";      break;
667     case Type::X86_FP80TyID:  Result += "f80";      break;
668     case Type::FP128TyID:     Result += "f128";     break;
669     case Type::PPC_FP128TyID: Result += "ppcf128";  break;
670     case Type::X86_MMXTyID:   Result += "x86mmx";   break;
671     case Type::IntegerTyID:
672       Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
673       break;
674     }
675   }
676   return Result;
677 }
678 
679 StringRef Intrinsic::getName(ID id) {
680   assert(id < num_intrinsics && "Invalid intrinsic ID!");
681   assert(!Intrinsic::isOverloaded(id) &&
682          "This version of getName does not support overloading");
683   return IntrinsicNameTable[id];
684 }
685 
686 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
687   assert(id < num_intrinsics && "Invalid intrinsic ID!");
688   std::string Result(IntrinsicNameTable[id]);
689   for (Type *Ty : Tys) {
690     Result += "." + getMangledTypeStr(Ty);
691   }
692   return Result;
693 }
694 
695 /// IIT_Info - These are enumerators that describe the entries returned by the
696 /// getIntrinsicInfoTableEntries function.
697 ///
698 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
699 enum IIT_Info {
700   // Common values should be encoded with 0-15.
701   IIT_Done = 0,
702   IIT_I1   = 1,
703   IIT_I8   = 2,
704   IIT_I16  = 3,
705   IIT_I32  = 4,
706   IIT_I64  = 5,
707   IIT_F16  = 6,
708   IIT_F32  = 7,
709   IIT_F64  = 8,
710   IIT_V2   = 9,
711   IIT_V4   = 10,
712   IIT_V8   = 11,
713   IIT_V16  = 12,
714   IIT_V32  = 13,
715   IIT_PTR  = 14,
716   IIT_ARG  = 15,
717 
718   // Values from 16+ are only encodable with the inefficient encoding.
719   IIT_V64  = 16,
720   IIT_MMX  = 17,
721   IIT_TOKEN = 18,
722   IIT_METADATA = 19,
723   IIT_EMPTYSTRUCT = 20,
724   IIT_STRUCT2 = 21,
725   IIT_STRUCT3 = 22,
726   IIT_STRUCT4 = 23,
727   IIT_STRUCT5 = 24,
728   IIT_EXTEND_ARG = 25,
729   IIT_TRUNC_ARG = 26,
730   IIT_ANYPTR = 27,
731   IIT_V1   = 28,
732   IIT_VARARG = 29,
733   IIT_HALF_VEC_ARG = 30,
734   IIT_SAME_VEC_WIDTH_ARG = 31,
735   IIT_PTR_TO_ARG = 32,
736   IIT_PTR_TO_ELT = 33,
737   IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
738   IIT_I128 = 35,
739   IIT_V512 = 36,
740   IIT_V1024 = 37,
741   IIT_STRUCT6 = 38,
742   IIT_STRUCT7 = 39,
743   IIT_STRUCT8 = 40,
744   IIT_F128 = 41,
745   IIT_VEC_ELEMENT = 42,
746   IIT_SCALABLE_VEC = 43,
747   IIT_SUBDIVIDE2_ARG = 44,
748   IIT_SUBDIVIDE4_ARG = 45,
749   IIT_VEC_OF_BITCASTS_TO_INT = 46,
750   IIT_V128 = 47,
751   IIT_BF16 = 48
752 };
753 
754 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
755                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
756   using namespace Intrinsic;
757 
758   bool IsScalableVector = false;
759   if (NextElt > 0) {
760     IIT_Info LastInfo = IIT_Info(Infos[NextElt - 1]);
761     IsScalableVector = (LastInfo == IIT_SCALABLE_VEC);
762   }
763 
764   IIT_Info Info = IIT_Info(Infos[NextElt++]);
765   unsigned StructElts = 2;
766 
767   switch (Info) {
768   case IIT_Done:
769     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
770     return;
771   case IIT_VARARG:
772     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
773     return;
774   case IIT_MMX:
775     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
776     return;
777   case IIT_TOKEN:
778     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
779     return;
780   case IIT_METADATA:
781     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
782     return;
783   case IIT_F16:
784     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
785     return;
786   case IIT_BF16:
787     OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));
788     return;
789   case IIT_F32:
790     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
791     return;
792   case IIT_F64:
793     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
794     return;
795   case IIT_F128:
796     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
797     return;
798   case IIT_I1:
799     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
800     return;
801   case IIT_I8:
802     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
803     return;
804   case IIT_I16:
805     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
806     return;
807   case IIT_I32:
808     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
809     return;
810   case IIT_I64:
811     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
812     return;
813   case IIT_I128:
814     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
815     return;
816   case IIT_V1:
817     OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector));
818     DecodeIITType(NextElt, Infos, OutputTable);
819     return;
820   case IIT_V2:
821     OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector));
822     DecodeIITType(NextElt, Infos, OutputTable);
823     return;
824   case IIT_V4:
825     OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector));
826     DecodeIITType(NextElt, Infos, OutputTable);
827     return;
828   case IIT_V8:
829     OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector));
830     DecodeIITType(NextElt, Infos, OutputTable);
831     return;
832   case IIT_V16:
833     OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector));
834     DecodeIITType(NextElt, Infos, OutputTable);
835     return;
836   case IIT_V32:
837     OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector));
838     DecodeIITType(NextElt, Infos, OutputTable);
839     return;
840   case IIT_V64:
841     OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector));
842     DecodeIITType(NextElt, Infos, OutputTable);
843     return;
844   case IIT_V128:
845     OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector));
846     DecodeIITType(NextElt, Infos, OutputTable);
847     return;
848   case IIT_V512:
849     OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector));
850     DecodeIITType(NextElt, Infos, OutputTable);
851     return;
852   case IIT_V1024:
853     OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector));
854     DecodeIITType(NextElt, Infos, OutputTable);
855     return;
856   case IIT_PTR:
857     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
858     DecodeIITType(NextElt, Infos, OutputTable);
859     return;
860   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
861     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
862                                              Infos[NextElt++]));
863     DecodeIITType(NextElt, Infos, OutputTable);
864     return;
865   }
866   case IIT_ARG: {
867     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
868     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
869     return;
870   }
871   case IIT_EXTEND_ARG: {
872     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
873     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
874                                              ArgInfo));
875     return;
876   }
877   case IIT_TRUNC_ARG: {
878     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
879     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
880                                              ArgInfo));
881     return;
882   }
883   case IIT_HALF_VEC_ARG: {
884     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
885     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
886                                              ArgInfo));
887     return;
888   }
889   case IIT_SAME_VEC_WIDTH_ARG: {
890     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
891     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
892                                              ArgInfo));
893     return;
894   }
895   case IIT_PTR_TO_ARG: {
896     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
897     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
898                                              ArgInfo));
899     return;
900   }
901   case IIT_PTR_TO_ELT: {
902     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
903     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
904     return;
905   }
906   case IIT_VEC_OF_ANYPTRS_TO_ELT: {
907     unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
908     unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
909     OutputTable.push_back(
910         IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
911     return;
912   }
913   case IIT_EMPTYSTRUCT:
914     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
915     return;
916   case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH;
917   case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH;
918   case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH;
919   case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
920   case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
921   case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
922   case IIT_STRUCT2: {
923     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
924 
925     for (unsigned i = 0; i != StructElts; ++i)
926       DecodeIITType(NextElt, Infos, OutputTable);
927     return;
928   }
929   case IIT_SUBDIVIDE2_ARG: {
930     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
931     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument,
932                                              ArgInfo));
933     return;
934   }
935   case IIT_SUBDIVIDE4_ARG: {
936     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
937     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument,
938                                              ArgInfo));
939     return;
940   }
941   case IIT_VEC_ELEMENT: {
942     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
943     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,
944                                              ArgInfo));
945     return;
946   }
947   case IIT_SCALABLE_VEC: {
948     DecodeIITType(NextElt, Infos, OutputTable);
949     return;
950   }
951   case IIT_VEC_OF_BITCASTS_TO_INT: {
952     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
953     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt,
954                                              ArgInfo));
955     return;
956   }
957   }
958   llvm_unreachable("unhandled");
959 }
960 
961 #define GET_INTRINSIC_GENERATOR_GLOBAL
962 #include "llvm/IR/IntrinsicImpl.inc"
963 #undef GET_INTRINSIC_GENERATOR_GLOBAL
964 
965 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
966                                              SmallVectorImpl<IITDescriptor> &T){
967   // Check to see if the intrinsic's type was expressible by the table.
968   unsigned TableVal = IIT_Table[id-1];
969 
970   // Decode the TableVal into an array of IITValues.
971   SmallVector<unsigned char, 8> IITValues;
972   ArrayRef<unsigned char> IITEntries;
973   unsigned NextElt = 0;
974   if ((TableVal >> 31) != 0) {
975     // This is an offset into the IIT_LongEncodingTable.
976     IITEntries = IIT_LongEncodingTable;
977 
978     // Strip sentinel bit.
979     NextElt = (TableVal << 1) >> 1;
980   } else {
981     // Decode the TableVal into an array of IITValues.  If the entry was encoded
982     // into a single word in the table itself, decode it now.
983     do {
984       IITValues.push_back(TableVal & 0xF);
985       TableVal >>= 4;
986     } while (TableVal);
987 
988     IITEntries = IITValues;
989     NextElt = 0;
990   }
991 
992   // Okay, decode the table into the output vector of IITDescriptors.
993   DecodeIITType(NextElt, IITEntries, T);
994   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
995     DecodeIITType(NextElt, IITEntries, T);
996 }
997 
998 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
999                              ArrayRef<Type*> Tys, LLVMContext &Context) {
1000   using namespace Intrinsic;
1001 
1002   IITDescriptor D = Infos.front();
1003   Infos = Infos.slice(1);
1004 
1005   switch (D.Kind) {
1006   case IITDescriptor::Void: return Type::getVoidTy(Context);
1007   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
1008   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
1009   case IITDescriptor::Token: return Type::getTokenTy(Context);
1010   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
1011   case IITDescriptor::Half: return Type::getHalfTy(Context);
1012   case IITDescriptor::BFloat: return Type::getBFloatTy(Context);
1013   case IITDescriptor::Float: return Type::getFloatTy(Context);
1014   case IITDescriptor::Double: return Type::getDoubleTy(Context);
1015   case IITDescriptor::Quad: return Type::getFP128Ty(Context);
1016 
1017   case IITDescriptor::Integer:
1018     return IntegerType::get(Context, D.Integer_Width);
1019   case IITDescriptor::Vector:
1020     return VectorType::get(DecodeFixedType(Infos, Tys, Context),
1021                            D.Vector_Width);
1022   case IITDescriptor::Pointer:
1023     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
1024                             D.Pointer_AddressSpace);
1025   case IITDescriptor::Struct: {
1026     SmallVector<Type *, 8> Elts;
1027     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1028       Elts.push_back(DecodeFixedType(Infos, Tys, Context));
1029     return StructType::get(Context, Elts);
1030   }
1031   case IITDescriptor::Argument:
1032     return Tys[D.getArgumentNumber()];
1033   case IITDescriptor::ExtendArgument: {
1034     Type *Ty = Tys[D.getArgumentNumber()];
1035     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1036       return VectorType::getExtendedElementVectorType(VTy);
1037 
1038     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
1039   }
1040   case IITDescriptor::TruncArgument: {
1041     Type *Ty = Tys[D.getArgumentNumber()];
1042     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1043       return VectorType::getTruncatedElementVectorType(VTy);
1044 
1045     IntegerType *ITy = cast<IntegerType>(Ty);
1046     assert(ITy->getBitWidth() % 2 == 0);
1047     return IntegerType::get(Context, ITy->getBitWidth() / 2);
1048   }
1049   case IITDescriptor::Subdivide2Argument:
1050   case IITDescriptor::Subdivide4Argument: {
1051     Type *Ty = Tys[D.getArgumentNumber()];
1052     VectorType *VTy = dyn_cast<VectorType>(Ty);
1053     assert(VTy && "Expected an argument of Vector Type");
1054     int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1055     return VectorType::getSubdividedVectorType(VTy, SubDivs);
1056   }
1057   case IITDescriptor::HalfVecArgument:
1058     return VectorType::getHalfElementsVectorType(cast<VectorType>(
1059                                                   Tys[D.getArgumentNumber()]));
1060   case IITDescriptor::SameVecWidthArgument: {
1061     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
1062     Type *Ty = Tys[D.getArgumentNumber()];
1063     if (auto *VTy = dyn_cast<VectorType>(Ty))
1064       return VectorType::get(EltTy, VTy->getElementCount());
1065     return EltTy;
1066   }
1067   case IITDescriptor::PtrToArgument: {
1068     Type *Ty = Tys[D.getArgumentNumber()];
1069     return PointerType::getUnqual(Ty);
1070   }
1071   case IITDescriptor::PtrToElt: {
1072     Type *Ty = Tys[D.getArgumentNumber()];
1073     VectorType *VTy = dyn_cast<VectorType>(Ty);
1074     if (!VTy)
1075       llvm_unreachable("Expected an argument of Vector Type");
1076     Type *EltTy = VTy->getElementType();
1077     return PointerType::getUnqual(EltTy);
1078   }
1079   case IITDescriptor::VecElementArgument: {
1080     Type *Ty = Tys[D.getArgumentNumber()];
1081     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1082       return VTy->getElementType();
1083     llvm_unreachable("Expected an argument of Vector Type");
1084   }
1085   case IITDescriptor::VecOfBitcastsToInt: {
1086     Type *Ty = Tys[D.getArgumentNumber()];
1087     VectorType *VTy = dyn_cast<VectorType>(Ty);
1088     assert(VTy && "Expected an argument of Vector Type");
1089     return VectorType::getInteger(VTy);
1090   }
1091   case IITDescriptor::VecOfAnyPtrsToElt:
1092     // Return the overloaded type (which determines the pointers address space)
1093     return Tys[D.getOverloadArgNumber()];
1094   }
1095   llvm_unreachable("unhandled");
1096 }
1097 
1098 FunctionType *Intrinsic::getType(LLVMContext &Context,
1099                                  ID id, ArrayRef<Type*> Tys) {
1100   SmallVector<IITDescriptor, 8> Table;
1101   getIntrinsicInfoTableEntries(id, Table);
1102 
1103   ArrayRef<IITDescriptor> TableRef = Table;
1104   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
1105 
1106   SmallVector<Type*, 8> ArgTys;
1107   while (!TableRef.empty())
1108     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
1109 
1110   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
1111   // If we see void type as the type of the last argument, it is vararg intrinsic
1112   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
1113     ArgTys.pop_back();
1114     return FunctionType::get(ResultTy, ArgTys, true);
1115   }
1116   return FunctionType::get(ResultTy, ArgTys, false);
1117 }
1118 
1119 bool Intrinsic::isOverloaded(ID id) {
1120 #define GET_INTRINSIC_OVERLOAD_TABLE
1121 #include "llvm/IR/IntrinsicImpl.inc"
1122 #undef GET_INTRINSIC_OVERLOAD_TABLE
1123 }
1124 
1125 bool Intrinsic::isLeaf(ID id) {
1126   switch (id) {
1127   default:
1128     return true;
1129 
1130   case Intrinsic::experimental_gc_statepoint:
1131   case Intrinsic::experimental_patchpoint_void:
1132   case Intrinsic::experimental_patchpoint_i64:
1133     return false;
1134   }
1135 }
1136 
1137 /// This defines the "Intrinsic::getAttributes(ID id)" method.
1138 #define GET_INTRINSIC_ATTRIBUTES
1139 #include "llvm/IR/IntrinsicImpl.inc"
1140 #undef GET_INTRINSIC_ATTRIBUTES
1141 
1142 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
1143   // There can never be multiple globals with the same name of different types,
1144   // because intrinsics must be a specific type.
1145   return cast<Function>(
1146       M->getOrInsertFunction(getName(id, Tys),
1147                              getType(M->getContext(), id, Tys))
1148           .getCallee());
1149 }
1150 
1151 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
1152 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1153 #include "llvm/IR/IntrinsicImpl.inc"
1154 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1155 
1156 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
1157 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1158 #include "llvm/IR/IntrinsicImpl.inc"
1159 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1160 
1161 using DeferredIntrinsicMatchPair =
1162     std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
1163 
1164 static bool matchIntrinsicType(
1165     Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
1166     SmallVectorImpl<Type *> &ArgTys,
1167     SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
1168     bool IsDeferredCheck) {
1169   using namespace Intrinsic;
1170 
1171   // If we ran out of descriptors, there are too many arguments.
1172   if (Infos.empty()) return true;
1173 
1174   // Do this before slicing off the 'front' part
1175   auto InfosRef = Infos;
1176   auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
1177     DeferredChecks.emplace_back(T, InfosRef);
1178     return false;
1179   };
1180 
1181   IITDescriptor D = Infos.front();
1182   Infos = Infos.slice(1);
1183 
1184   switch (D.Kind) {
1185     case IITDescriptor::Void: return !Ty->isVoidTy();
1186     case IITDescriptor::VarArg: return true;
1187     case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
1188     case IITDescriptor::Token: return !Ty->isTokenTy();
1189     case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1190     case IITDescriptor::Half: return !Ty->isHalfTy();
1191     case IITDescriptor::BFloat: return !Ty->isBFloatTy();
1192     case IITDescriptor::Float: return !Ty->isFloatTy();
1193     case IITDescriptor::Double: return !Ty->isDoubleTy();
1194     case IITDescriptor::Quad: return !Ty->isFP128Ty();
1195     case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1196     case IITDescriptor::Vector: {
1197       VectorType *VT = dyn_cast<VectorType>(Ty);
1198       return !VT || VT->getElementCount() != D.Vector_Width ||
1199              matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
1200                                 DeferredChecks, IsDeferredCheck);
1201     }
1202     case IITDescriptor::Pointer: {
1203       PointerType *PT = dyn_cast<PointerType>(Ty);
1204       return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
1205              matchIntrinsicType(PT->getElementType(), Infos, ArgTys,
1206                                 DeferredChecks, IsDeferredCheck);
1207     }
1208 
1209     case IITDescriptor::Struct: {
1210       StructType *ST = dyn_cast<StructType>(Ty);
1211       if (!ST || ST->getNumElements() != D.Struct_NumElements)
1212         return true;
1213 
1214       for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1215         if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
1216                                DeferredChecks, IsDeferredCheck))
1217           return true;
1218       return false;
1219     }
1220 
1221     case IITDescriptor::Argument:
1222       // If this is the second occurrence of an argument,
1223       // verify that the later instance matches the previous instance.
1224       if (D.getArgumentNumber() < ArgTys.size())
1225         return Ty != ArgTys[D.getArgumentNumber()];
1226 
1227       if (D.getArgumentNumber() > ArgTys.size() ||
1228           D.getArgumentKind() == IITDescriptor::AK_MatchType)
1229         return IsDeferredCheck || DeferCheck(Ty);
1230 
1231       assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
1232              "Table consistency error");
1233       ArgTys.push_back(Ty);
1234 
1235       switch (D.getArgumentKind()) {
1236         case IITDescriptor::AK_Any:        return false; // Success
1237         case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1238         case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
1239         case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
1240         case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1241         default:                           break;
1242       }
1243       llvm_unreachable("all argument kinds not covered");
1244 
1245     case IITDescriptor::ExtendArgument: {
1246       // If this is a forward reference, defer the check for later.
1247       if (D.getArgumentNumber() >= ArgTys.size())
1248         return IsDeferredCheck || DeferCheck(Ty);
1249 
1250       Type *NewTy = ArgTys[D.getArgumentNumber()];
1251       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1252         NewTy = VectorType::getExtendedElementVectorType(VTy);
1253       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1254         NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
1255       else
1256         return true;
1257 
1258       return Ty != NewTy;
1259     }
1260     case IITDescriptor::TruncArgument: {
1261       // If this is a forward reference, defer the check for later.
1262       if (D.getArgumentNumber() >= ArgTys.size())
1263         return IsDeferredCheck || DeferCheck(Ty);
1264 
1265       Type *NewTy = ArgTys[D.getArgumentNumber()];
1266       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1267         NewTy = VectorType::getTruncatedElementVectorType(VTy);
1268       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1269         NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
1270       else
1271         return true;
1272 
1273       return Ty != NewTy;
1274     }
1275     case IITDescriptor::HalfVecArgument:
1276       // If this is a forward reference, defer the check for later.
1277       if (D.getArgumentNumber() >= ArgTys.size())
1278         return IsDeferredCheck || DeferCheck(Ty);
1279       return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1280              VectorType::getHalfElementsVectorType(
1281                      cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1282     case IITDescriptor::SameVecWidthArgument: {
1283       if (D.getArgumentNumber() >= ArgTys.size()) {
1284         // Defer check and subsequent check for the vector element type.
1285         Infos = Infos.slice(1);
1286         return IsDeferredCheck || DeferCheck(Ty);
1287       }
1288       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1289       auto *ThisArgType = dyn_cast<VectorType>(Ty);
1290       // Both must be vectors of the same number of elements or neither.
1291       if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
1292         return true;
1293       Type *EltTy = Ty;
1294       if (ThisArgType) {
1295         if (ReferenceType->getElementCount() !=
1296             ThisArgType->getElementCount())
1297           return true;
1298         EltTy = ThisArgType->getElementType();
1299       }
1300       return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
1301                                 IsDeferredCheck);
1302     }
1303     case IITDescriptor::PtrToArgument: {
1304       if (D.getArgumentNumber() >= ArgTys.size())
1305         return IsDeferredCheck || DeferCheck(Ty);
1306       Type * ReferenceType = ArgTys[D.getArgumentNumber()];
1307       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1308       return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
1309     }
1310     case IITDescriptor::PtrToElt: {
1311       if (D.getArgumentNumber() >= ArgTys.size())
1312         return IsDeferredCheck || DeferCheck(Ty);
1313       VectorType * ReferenceType =
1314         dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
1315       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1316 
1317       return (!ThisArgType || !ReferenceType ||
1318               ThisArgType->getElementType() != ReferenceType->getElementType());
1319     }
1320     case IITDescriptor::VecOfAnyPtrsToElt: {
1321       unsigned RefArgNumber = D.getRefArgNumber();
1322       if (RefArgNumber >= ArgTys.size()) {
1323         if (IsDeferredCheck)
1324           return true;
1325         // If forward referencing, already add the pointer-vector type and
1326         // defer the checks for later.
1327         ArgTys.push_back(Ty);
1328         return DeferCheck(Ty);
1329       }
1330 
1331       if (!IsDeferredCheck){
1332         assert(D.getOverloadArgNumber() == ArgTys.size() &&
1333                "Table consistency error");
1334         ArgTys.push_back(Ty);
1335       }
1336 
1337       // Verify the overloaded type "matches" the Ref type.
1338       // i.e. Ty is a vector with the same width as Ref.
1339       // Composed of pointers to the same element type as Ref.
1340       VectorType *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
1341       VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1342       if (!ThisArgVecTy || !ReferenceType ||
1343           (ReferenceType->getNumElements() != ThisArgVecTy->getNumElements()))
1344         return true;
1345       PointerType *ThisArgEltTy =
1346           dyn_cast<PointerType>(ThisArgVecTy->getElementType());
1347       if (!ThisArgEltTy)
1348         return true;
1349       return ThisArgEltTy->getElementType() != ReferenceType->getElementType();
1350     }
1351     case IITDescriptor::VecElementArgument: {
1352       if (D.getArgumentNumber() >= ArgTys.size())
1353         return IsDeferredCheck ? true : DeferCheck(Ty);
1354       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1355       return !ReferenceType || Ty != ReferenceType->getElementType();
1356     }
1357     case IITDescriptor::Subdivide2Argument:
1358     case IITDescriptor::Subdivide4Argument: {
1359       // If this is a forward reference, defer the check for later.
1360       if (D.getArgumentNumber() >= ArgTys.size())
1361         return IsDeferredCheck || DeferCheck(Ty);
1362 
1363       Type *NewTy = ArgTys[D.getArgumentNumber()];
1364       if (auto *VTy = dyn_cast<VectorType>(NewTy)) {
1365         int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1366         NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs);
1367         return Ty != NewTy;
1368       }
1369       return true;
1370     }
1371     case IITDescriptor::VecOfBitcastsToInt: {
1372       if (D.getArgumentNumber() >= ArgTys.size())
1373         return IsDeferredCheck || DeferCheck(Ty);
1374       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1375       auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1376       if (!ThisArgVecTy || !ReferenceType)
1377         return true;
1378       return ThisArgVecTy != VectorType::getInteger(ReferenceType);
1379     }
1380   }
1381   llvm_unreachable("unhandled");
1382 }
1383 
1384 Intrinsic::MatchIntrinsicTypesResult
1385 Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
1386                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
1387                                    SmallVectorImpl<Type *> &ArgTys) {
1388   SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
1389   if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
1390                          false))
1391     return MatchIntrinsicTypes_NoMatchRet;
1392 
1393   unsigned NumDeferredReturnChecks = DeferredChecks.size();
1394 
1395   for (auto Ty : FTy->params())
1396     if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
1397       return MatchIntrinsicTypes_NoMatchArg;
1398 
1399   for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
1400     DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
1401     if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
1402                            true))
1403       return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
1404                                          : MatchIntrinsicTypes_NoMatchArg;
1405   }
1406 
1407   return MatchIntrinsicTypes_Match;
1408 }
1409 
1410 bool
1411 Intrinsic::matchIntrinsicVarArg(bool isVarArg,
1412                                 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
1413   // If there are no descriptors left, then it can't be a vararg.
1414   if (Infos.empty())
1415     return isVarArg;
1416 
1417   // There should be only one descriptor remaining at this point.
1418   if (Infos.size() != 1)
1419     return true;
1420 
1421   // Check and verify the descriptor.
1422   IITDescriptor D = Infos.front();
1423   Infos = Infos.slice(1);
1424   if (D.Kind == IITDescriptor::VarArg)
1425     return !isVarArg;
1426 
1427   return true;
1428 }
1429 
1430 Optional<Function*> Intrinsic::remangleIntrinsicFunction(Function *F) {
1431   Intrinsic::ID ID = F->getIntrinsicID();
1432   if (!ID)
1433     return None;
1434 
1435   FunctionType *FTy = F->getFunctionType();
1436   // Accumulate an array of overloaded types for the given intrinsic
1437   SmallVector<Type *, 4> ArgTys;
1438   {
1439     SmallVector<Intrinsic::IITDescriptor, 8> Table;
1440     getIntrinsicInfoTableEntries(ID, Table);
1441     ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1442 
1443     if (Intrinsic::matchIntrinsicSignature(FTy, TableRef, ArgTys))
1444       return None;
1445     if (Intrinsic::matchIntrinsicVarArg(FTy->isVarArg(), TableRef))
1446       return None;
1447   }
1448 
1449   StringRef Name = F->getName();
1450   if (Name == Intrinsic::getName(ID, ArgTys))
1451     return None;
1452 
1453   auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
1454   NewDecl->setCallingConv(F->getCallingConv());
1455   assert(NewDecl->getFunctionType() == FTy && "Shouldn't change the signature");
1456   return NewDecl;
1457 }
1458 
1459 /// hasAddressTaken - returns true if there are any uses of this function
1460 /// other than direct calls or invokes to it.
1461 bool Function::hasAddressTaken(const User* *PutOffender) const {
1462   for (const Use &U : uses()) {
1463     const User *FU = U.getUser();
1464     if (isa<BlockAddress>(FU))
1465       continue;
1466     const auto *Call = dyn_cast<CallBase>(FU);
1467     if (!Call) {
1468       if (PutOffender)
1469         *PutOffender = FU;
1470       return true;
1471     }
1472     if (!Call->isCallee(&U)) {
1473       if (PutOffender)
1474         *PutOffender = FU;
1475       return true;
1476     }
1477   }
1478   return false;
1479 }
1480 
1481 bool Function::isDefTriviallyDead() const {
1482   // Check the linkage
1483   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1484       !hasAvailableExternallyLinkage())
1485     return false;
1486 
1487   // Check if the function is used by anything other than a blockaddress.
1488   for (const User *U : users())
1489     if (!isa<BlockAddress>(U))
1490       return false;
1491 
1492   return true;
1493 }
1494 
1495 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
1496 /// setjmp or other function that gcc recognizes as "returning twice".
1497 bool Function::callsFunctionThatReturnsTwice() const {
1498   for (const Instruction &I : instructions(this))
1499     if (const auto *Call = dyn_cast<CallBase>(&I))
1500       if (Call->hasFnAttr(Attribute::ReturnsTwice))
1501         return true;
1502 
1503   return false;
1504 }
1505 
1506 Constant *Function::getPersonalityFn() const {
1507   assert(hasPersonalityFn() && getNumOperands());
1508   return cast<Constant>(Op<0>());
1509 }
1510 
1511 void Function::setPersonalityFn(Constant *Fn) {
1512   setHungoffOperand<0>(Fn);
1513   setValueSubclassDataBit(3, Fn != nullptr);
1514 }
1515 
1516 Constant *Function::getPrefixData() const {
1517   assert(hasPrefixData() && getNumOperands());
1518   return cast<Constant>(Op<1>());
1519 }
1520 
1521 void Function::setPrefixData(Constant *PrefixData) {
1522   setHungoffOperand<1>(PrefixData);
1523   setValueSubclassDataBit(1, PrefixData != nullptr);
1524 }
1525 
1526 Constant *Function::getPrologueData() const {
1527   assert(hasPrologueData() && getNumOperands());
1528   return cast<Constant>(Op<2>());
1529 }
1530 
1531 void Function::setPrologueData(Constant *PrologueData) {
1532   setHungoffOperand<2>(PrologueData);
1533   setValueSubclassDataBit(2, PrologueData != nullptr);
1534 }
1535 
1536 void Function::allocHungoffUselist() {
1537   // If we've already allocated a uselist, stop here.
1538   if (getNumOperands())
1539     return;
1540 
1541   allocHungoffUses(3, /*IsPhi=*/ false);
1542   setNumHungOffUseOperands(3);
1543 
1544   // Initialize the uselist with placeholder operands to allow traversal.
1545   auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
1546   Op<0>().set(CPN);
1547   Op<1>().set(CPN);
1548   Op<2>().set(CPN);
1549 }
1550 
1551 template <int Idx>
1552 void Function::setHungoffOperand(Constant *C) {
1553   if (C) {
1554     allocHungoffUselist();
1555     Op<Idx>().set(C);
1556   } else if (getNumOperands()) {
1557     Op<Idx>().set(
1558         ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
1559   }
1560 }
1561 
1562 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
1563   assert(Bit < 16 && "SubclassData contains only 16 bits");
1564   if (On)
1565     setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
1566   else
1567     setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
1568 }
1569 
1570 void Function::setEntryCount(ProfileCount Count,
1571                              const DenseSet<GlobalValue::GUID> *S) {
1572   assert(Count.hasValue());
1573 #if !defined(NDEBUG)
1574   auto PrevCount = getEntryCount();
1575   assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType());
1576 #endif
1577 
1578   auto ImportGUIDs = getImportGUIDs();
1579   if (S == nullptr && ImportGUIDs.size())
1580     S = &ImportGUIDs;
1581 
1582   MDBuilder MDB(getContext());
1583   setMetadata(
1584       LLVMContext::MD_prof,
1585       MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
1586 }
1587 
1588 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
1589                              const DenseSet<GlobalValue::GUID> *Imports) {
1590   setEntryCount(ProfileCount(Count, Type), Imports);
1591 }
1592 
1593 ProfileCount Function::getEntryCount(bool AllowSynthetic) const {
1594   MDNode *MD = getMetadata(LLVMContext::MD_prof);
1595   if (MD && MD->getOperand(0))
1596     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
1597       if (MDS->getString().equals("function_entry_count")) {
1598         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1599         uint64_t Count = CI->getValue().getZExtValue();
1600         // A value of -1 is used for SamplePGO when there were no samples.
1601         // Treat this the same as unknown.
1602         if (Count == (uint64_t)-1)
1603           return ProfileCount::getInvalid();
1604         return ProfileCount(Count, PCT_Real);
1605       } else if (AllowSynthetic &&
1606                  MDS->getString().equals("synthetic_function_entry_count")) {
1607         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1608         uint64_t Count = CI->getValue().getZExtValue();
1609         return ProfileCount(Count, PCT_Synthetic);
1610       }
1611     }
1612   return ProfileCount::getInvalid();
1613 }
1614 
1615 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
1616   DenseSet<GlobalValue::GUID> R;
1617   if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
1618     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1619       if (MDS->getString().equals("function_entry_count"))
1620         for (unsigned i = 2; i < MD->getNumOperands(); i++)
1621           R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
1622                        ->getValue()
1623                        .getZExtValue());
1624   return R;
1625 }
1626 
1627 void Function::setSectionPrefix(StringRef Prefix) {
1628   MDBuilder MDB(getContext());
1629   setMetadata(LLVMContext::MD_section_prefix,
1630               MDB.createFunctionSectionPrefix(Prefix));
1631 }
1632 
1633 Optional<StringRef> Function::getSectionPrefix() const {
1634   if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
1635     assert(cast<MDString>(MD->getOperand(0))
1636                ->getString()
1637                .equals("function_section_prefix") &&
1638            "Metadata not match");
1639     return cast<MDString>(MD->getOperand(1))->getString();
1640   }
1641   return None;
1642 }
1643 
1644 bool Function::nullPointerIsDefined() const {
1645   return hasFnAttribute(Attribute::NullPointerIsValid);
1646 }
1647 
1648 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
1649   if (F && F->nullPointerIsDefined())
1650     return true;
1651 
1652   if (AS != 0)
1653     return true;
1654 
1655   return false;
1656 }
1657