-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSILInstruction.h
4470 lines (3600 loc) · 150 KB
/
SILInstruction.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- SILInstruction.h - Instructions for SIL code -----------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the high-level SILInstruction class used for SIL code.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SIL_INSTRUCTION_H
#define SWIFT_SIL_INSTRUCTION_H
#include "llvm/ADT/ilist_node.h"
#include "llvm/ADT/ilist.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "swift/AST/Builtins.h"
#include "swift/SIL/Consumption.h"
#include "swift/SIL/SILAllocated.h"
#include "swift/SIL/SILLocation.h"
#include "swift/SIL/SILSuccessor.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/SILValue.h"
namespace swift {
class DeclRefExpr;
class FloatLiteralExpr;
class FuncDecl;
class IntegerLiteralExpr;
class SILBasicBlock;
class SILBuilder;
class SILDebugLocation;
class SILDebugScope;
class SILFunction;
class SILGlobalVariable;
class SILType;
class SILArgument;
class Stmt;
class StringLiteralExpr;
class Substitution;
class ValueDecl;
class VarDecl;
class FunctionRefInst;
template <typename ImplClass> class SILClonerWithScopes;
/// This is the root class for all instructions that can be used as the contents
/// of a Swift SILBasicBlock.
class SILInstruction : public ValueBase,public llvm::ilist_node<SILInstruction>{
friend struct llvm::ilist_traits<SILInstruction>;
friend struct llvm::ilist_traits<SILBasicBlock>;
/// A backreference to the containing basic block. This is maintained by
/// ilist_traits<SILInstruction>.
SILBasicBlock *ParentBB;
/// This instruction's containing lexical scope and source location
/// used for debug info and diagnostics.
SILDebugLocation &Location;
friend struct llvm::ilist_sentinel_traits<SILInstruction>;
SILInstruction() = delete;
void operator=(const SILInstruction &) = delete;
void operator delete(void *Ptr, size_t) = delete;
/// Check any special state of instructions that are not represented in the
/// instructions operands/type.
bool hasIdenticalState(const SILInstruction *RHS) const;
/// Update this instruction's SILDebugScope. This function should
/// never be called directly. Use SILBuilder, SILBuilderWithScope or
/// SILClonerWithScope instead.
void setDebugScope(SILBuilder &B, const SILDebugScope *DS);
protected:
SILInstruction(ValueKind Kind, SILDebugLocation *DebugLoc, SILType Ty)
: ValueBase(Kind, Ty), ParentBB(0), Location(*DebugLoc) {}
SILInstruction(ValueKind Kind, SILDebugLocation *DebugLoc,
SILTypeList *TypeList = nullptr)
: ValueBase(Kind, TypeList), ParentBB(0), Location(*DebugLoc) {}
public:
/// Instructions should be allocated using a dedicated instruction allocation
/// function from the ContextTy.
template <typename ContextTy>
void *operator new(size_t Bytes, const ContextTy &C,
size_t Alignment = alignof(ValueBase)) {
return C.allocateInst(Bytes, Alignment);
}
enum class MemoryBehavior {
None,
/// The instruction may read memory.
MayRead,
/// \brief The instruction may write to memory.
MayWrite,
/// The instruction may read or write memory.
MayReadWrite,
/// \brief The instruction may have side effects not captured
/// solely by its users. Specifically, it can return,
/// release memory, or store. Note, alloc is not considered
/// to have side effects because its result/users represent
/// its effect.
MayHaveSideEffects,
};
/// Enumeration representing whether the execution of an instruction can
/// result in memory being released.
enum class ReleasingBehavior {
DoesNotRelease,
MayRelease,
};
const SILBasicBlock *getParent() const { return ParentBB; }
SILBasicBlock *getParent() { return ParentBB; }
SILFunction *getFunction();
const SILFunction *getFunction() const;
SILModule &getModule() const;
/// This instruction's source location (AST node).
SILLocation getLoc() const;
const SILDebugScope *getDebugScope() const;
SILDebugLocation &getDebugLocation() const { return Location; }
/// removeFromParent - This method unlinks 'self' from the containing basic
/// block, but does not delete it.
///
void removeFromParent();
/// eraseFromParent - This method unlinks 'self' from the containing basic
/// block and deletes it.
///
void eraseFromParent();
/// Unlink this instruction from its current basic block and insert it into
/// the basic block that Later lives in, right before Later.
void moveBefore(SILInstruction *Later);
/// Unlink this instruction from its current basic block and insert it into
/// the basic block that Earlier lives in, right after Earlier.
void moveAfter(SILInstruction *Earlier);
/// \brief Drops all uses that belong to this instruction.
void dropAllReferences();
/// \brief Replace all uses of this instruction with Undef.
///
/// TODO: This should be on ValueBase, but ValueBase currently does not have
/// access to a SILModule. If that ever changes, this method should move to
/// ValueBase.
void replaceAllUsesWithUndef();
/// Return the array of operands for this instruction.
ArrayRef<Operand> getAllOperands() const;
/// Return the array of mutable operands for this instruction.
MutableArrayRef<Operand> getAllOperands();
unsigned getNumOperands() const { return getAllOperands().size(); }
SILValue getOperand(unsigned Num) const { return getAllOperands()[Num].get();}
void setOperand(unsigned Num, SILValue V) { getAllOperands()[Num].set(V); }
void swapOperands(unsigned Num1, unsigned Num2) {
getAllOperands()[Num1].swap(getAllOperands()[Num2]);
}
MemoryBehavior getMemoryBehavior() const;
ReleasingBehavior getReleasingBehavior() const;
bool mayRelease() const;
/// Can this instruction abort the program in some manner?
bool mayTrap() const;
/// Returns true if the given instruction is completely identical to RHS.
bool isIdenticalTo(const SILInstruction *RHS) const {
return isIdenticalTo(RHS,
[](const SILValue &Op1, const SILValue &Op2) -> bool {
return Op1 == Op2; });
}
/// Returns true if the given instruction is completely identical to RHS,
/// using \p opEqual to compare operands.
///
template <typename OpCmp>
bool isIdenticalTo(const SILInstruction *RHS, OpCmp opEqual) const {
// Quick check if both instructions have the same kind, number of operands,
// and number of types. This should filter out most cases.
if (getKind() != RHS->getKind() ||
getNumOperands() != RHS->getNumOperands() ||
getNumTypes() != RHS->getNumTypes()) {
return false;
}
// Check types.
//
// Many instructions have only 1 type so it makes sense to check it first.
for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
if (getType(i) != RHS->getType(i))
return false;
// Check operands.
for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
if (!opEqual(getOperand(i), RHS->getOperand(i)))
return false;
// Check any special state of instructions that are not represented in the
// instructions operands/type.
return hasIdenticalState(RHS);
}
/// \brief Returns true if the instruction may have side effects.
///
/// Instructions that store into memory or change retain counts as well as
/// calls and deallocation instructions are considered to have side effects
/// that are not visible by merely examining their uses.
bool mayHaveSideEffects() const;
/// Returns true if the instruction may write to memory.
bool mayWriteToMemory() const {
MemoryBehavior B = getMemoryBehavior();
return B == MemoryBehavior::MayWrite ||
B == MemoryBehavior::MayReadWrite ||
B == MemoryBehavior::MayHaveSideEffects;
}
/// Returns true if the instruction may read from memory.
bool mayReadFromMemory() const {
MemoryBehavior B = getMemoryBehavior();
return B == MemoryBehavior::MayRead ||
B == MemoryBehavior::MayReadWrite ||
B == MemoryBehavior::MayHaveSideEffects;
}
/// Returns true if the instruction may read from or write to memory.
bool mayReadOrWriteMemory() const {
return getMemoryBehavior() != MemoryBehavior::None;
}
/// Returns true if the result of this instruction is a pointer to stack
/// allocated memory. In this case there must be an adjacent deallocating
/// instruction.
bool isAllocatingStack() const;
/// Returns true if this is the deallocation of a stack allocating instruction.
/// The first operand must be the allocating instruction.
bool isDeallocatingStack() const;
static bool classof(const ValueBase *V) {
return V->getKind() >= ValueKind::First_SILInstruction &&
V->getKind() <= ValueKind::Last_SILInstruction;
}
/// Create a new copy of this instruction, which retains all of the operands
/// and other information of this one. If an insertion point is specified,
/// then the new instruction is inserted before the specified point, otherwise
/// the new instruction is returned without a parent.
SILInstruction *clone(SILInstruction *InsertPt = nullptr);
/// Invoke an Instruction's destructor. This dispatches to the appropriate
/// leaf class destructor for the type of the instruction. This does not
/// deallocate the instruction.
static void destroy(SILInstruction *I);
/// Returns true if the instruction can be duplicated without any special
/// additional handling. It is important to know this information when
/// you perform such optimizations like e.g. jump-threading.
bool isTriviallyDuplicatable() const;
};
#ifndef NDEBUG
/// Pretty-print the MemoryBehavior.
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
SILInstruction::MemoryBehavior B);
#endif
/// A template base class for instructions that take a single SILValue operand
/// and has no result or a single value result.
template<ValueKind KIND, typename BASE = SILInstruction, bool HAS_RESULT = true>
class UnaryInstructionBase : public BASE {
FixedOperandList<1> Operands;
/// Check HAS_RESULT in enable_if predicates by injecting a dependency on
/// a template argument.
template<typename X>
struct has_result {
enum { value = HAS_RESULT };
};
public:
UnaryInstructionBase(SILDebugLocation *DebugLoc, SILValue Operand)
: BASE(KIND, DebugLoc), Operands(this, Operand) {}
template <typename X = void>
UnaryInstructionBase(
SILDebugLocation *DebugLoc, SILValue Operand,
typename std::enable_if<has_result<X>::value, SILType>::type Ty)
: BASE(KIND, DebugLoc, Ty), Operands(this, Operand) {}
template <typename X = void, typename... A>
UnaryInstructionBase(
SILDebugLocation *DebugLoc, SILValue Operand,
typename std::enable_if<has_result<X>::value, SILType>::type Ty,
A &&... args)
: BASE(KIND, DebugLoc, Ty, std::forward<A>(args)...),
Operands(this, Operand) {}
SILValue getOperand() const { return Operands[0].get(); }
void setOperand(SILValue V) { Operands[0].set(V); }
Operand &getOperandRef() { return Operands[0]; }
/// getType() is ok if this is known to only have one type.
template<typename X = void>
typename std::enable_if<has_result<X>::value, SILType>::type
getType(unsigned i = 0) const { return ValueBase::getType(i); }
ArrayRef<Operand> getAllOperands() const { return Operands.asArray(); }
MutableArrayRef<Operand> getAllOperands() { return Operands.asArray(); }
static bool classof(const ValueBase *V) {
return V->getKind() == KIND;
}
};
//===----------------------------------------------------------------------===//
// Allocation Instructions
//===----------------------------------------------------------------------===//
/// Abstract base class for allocation instructions, like alloc_stack, alloc_box
/// and alloc_ref, etc.
class AllocationInst : public SILInstruction {
protected:
AllocationInst(ValueKind Kind, SILDebugLocation *DebugLoc, SILType Ty)
: SILInstruction(Kind, DebugLoc, Ty) {}
AllocationInst(ValueKind Kind, SILDebugLocation *DebugLoc,
SILTypeList *TypeList = nullptr)
: SILInstruction(Kind, DebugLoc, TypeList) {}
public:
static bool classof(const ValueBase *V) {
return V->getKind() >= ValueKind::First_AllocationInst &&
V->getKind() <= ValueKind::Last_AllocationInst;
}
};
/// Base class for allocation/deallocation instructions where the allocation
/// can be promoted to the stack.
/// Note that IRGen can still decide to _not_ promote the allocation on the
/// stack.
class StackPromotable {
/// If true, the allocation can be done on the stack (the final decision is
/// in IRGen).
bool OnStack = false;
public:
StackPromotable(bool OnStack) : OnStack(OnStack) { }
bool canAllocOnStack() const { return OnStack; }
void setStackAllocatable() { OnStack = true; }
};
/// AllocStackInst - This represents the allocation of an unboxed (i.e., no
/// reference count) stack memory. The memory is provided uninitialized.
class AllocStackInst : public AllocationInst {
friend class SILBuilder;
AllocStackInst(SILDebugLocation *Loc, SILType elementType, SILFunction &F);
public:
/// getDecl - Return the underlying variable declaration associated with this
/// allocation, or null if this is a temporary allocation.
VarDecl *getDecl() const;
/// getElementType - Get the type of the allocated memory (as opposed to the
/// (second) type of the instruction itself, which will be an address type).
SILType getElementType() const {
return getType(1).getObjectType();
}
SILValue getContainerResult() const { return SILValue(this, 0); }
SILValue getAddressResult() const { return SILValue(this, 1); }
ArrayRef<Operand> getAllOperands() const { return {}; }
MutableArrayRef<Operand> getAllOperands() { return {}; }
static bool classof(const ValueBase *V) {
return V->getKind() == ValueKind::AllocStackInst;
}
};
/// AllocRefInst - This represents the primitive allocation of an instance
/// of a reference type. Aside from the reference count, the instance is
/// returned uninitialized.
class AllocRefInst : public AllocationInst, public StackPromotable {
friend class SILBuilder;
bool ObjC;
AllocRefInst(SILDebugLocation *Loc, SILType type, SILFunction &F, bool objc,
bool canBeOnStack);
public:
SILType getType(unsigned i = 0) const { return ValueBase::getType(i); }
ArrayRef<Operand> getAllOperands() const { return {}; }
MutableArrayRef<Operand> getAllOperands() { return {}; }
/// Whether to use Objective-C's allocation mechanism (+allocWithZone:).
bool isObjC() const { return ObjC; }
static bool classof(const ValueBase *V) {
return V->getKind() == ValueKind::AllocRefInst;
}
};
/// AllocRefDynamicInst - This represents the primitive allocation of
/// an instance of a reference type whose runtime type is provided by
/// the given metatype value. Aside from the reference count, the
/// instance is returned uninitialized.
class AllocRefDynamicInst
: public UnaryInstructionBase<ValueKind::AllocRefDynamicInst, AllocationInst>
{
friend class SILBuilder;
bool ObjC;
AllocRefDynamicInst(SILDebugLocation *DebugLoc, SILValue operand, SILType ty,
bool objc)
: UnaryInstructionBase(DebugLoc, operand, ty), ObjC(objc) {}
public:
/// Whether to use Objective-C's allocation mechanism (+allocWithZone:).
bool isObjC() const { return ObjC; }
};
/// AllocValueBufferInst - Allocate memory in a value buffer.
class AllocValueBufferInst :
public UnaryInstructionBase<ValueKind::AllocValueBufferInst,
AllocationInst> {
friend class SILBuilder;
AllocValueBufferInst(SILDebugLocation *DebugLoc, SILType valueType,
SILValue operand)
: UnaryInstructionBase(DebugLoc, operand, valueType.getAddressType()) {}
public:
SILType getValueType() const { return getType().getObjectType(); }
};
/// This represents the allocation of a heap box for a Swift value of some type.
/// The instruction returns two values. The first return value is the object
/// pointer with Builtin.NativeObject type. The second return value
/// is an address pointing to the contained element. The contained
/// element is uninitialized.
class AllocBoxInst : public AllocationInst {
friend class SILBuilder;
AllocBoxInst(SILDebugLocation *DebugLoc, SILType ElementType, SILFunction &F);
public:
SILType getElementType() const {
return getType(1).getObjectType();
}
SILValue getContainerResult() const { return SILValue(this, 0); }
SILValue getAddressResult() const { return SILValue(this, 1); }
/// getDecl - Return the underlying variable declaration associated with this
/// allocation, or null if this is a temporary allocation.
VarDecl *getDecl() const;
ArrayRef<Operand> getAllOperands() const { return {}; }
MutableArrayRef<Operand> getAllOperands() { return {}; }
static bool classof(const ValueBase *V) {
return V->getKind() == ValueKind::AllocBoxInst;
}
};
/// This represents the allocation of a heap box for an existential container.
/// The instruction returns two values. The first return value is the owner
/// pointer, which has the existential type. The second return value
/// is an address pointing to the contained element. The contained
/// value is uninitialized.
class AllocExistentialBoxInst : public AllocationInst {
friend class SILBuilder;
CanType ConcreteType;
ArrayRef<ProtocolConformance*> Conformances;
AllocExistentialBoxInst(SILDebugLocation *DebugLoc, SILType ExistentialType,
CanType ConcreteType, SILType ConcreteLoweredType,
ArrayRef<ProtocolConformance *> Conformances,
SILFunction *Parent);
static AllocExistentialBoxInst *
create(SILDebugLocation *DebugLoc, SILType ExistentialType,
CanType ConcreteType, SILType ConcreteLoweredType,
ArrayRef<ProtocolConformance *> Conformances, SILFunction *Parent);
public:
CanType getFormalConcreteType() const {
return ConcreteType;
}
SILType getExistentialType() const {
return getType(0);
}
SILType getLoweredConcreteType() const {
return getType(1);
}
ArrayRef<ProtocolConformance*> getConformances() const {
return Conformances;
}
SILValue getExistentialResult() const { return SILValue(this, 0); }
SILValue getValueAddressResult() const { return SILValue(this, 1); }
ArrayRef<Operand> getAllOperands() const { return {}; }
MutableArrayRef<Operand> getAllOperands() { return {}; }
static bool classof(const ValueBase *V) {
return V->getKind() == ValueKind::AllocExistentialBoxInst;
}
};
void *allocateApplyInst(SILFunction &F, size_t size, size_t align);
class PartialApplyInst;
/// ApplyInstBase - An abstract class for different kinds of function
/// application.
template <class Impl, class Base,
bool IsFullApply = !std::is_same<Impl, PartialApplyInst>::value>
class ApplyInstBase;
// The partial specialization for non-full applies. Note that the
// partial specialization for full applies inherits from this.
template <class Impl, class Base>
class ApplyInstBase<Impl, Base, false> : public Base {
enum {
Callee
};
/// The type of the callee with our substitutions applied.
SILType SubstCalleeType;
/// The number of tail-allocated substitutions, allocated after the operand
/// list's tail allocation.
unsigned NumSubstitutions;
/// Used for apply_inst instructions: true if the called function has an
/// error result but is not actually throwing.
bool NonThrowing;
/// The fixed operand is the callee; the rest are arguments.
TailAllocatedOperandList<1> Operands;
Substitution *getSubstitutionsStorage() {
return reinterpret_cast<Substitution*>(Operands.asArray().end());
}
const Substitution *getSubstitutionsStorage() const {
return reinterpret_cast<const Substitution*>(Operands.asArray().end());
}
protected:
template <class... As>
ApplyInstBase(ValueKind kind, SILDebugLocation *DebugLoc, SILValue callee,
SILType substCalleeType, ArrayRef<Substitution> substitutions,
ArrayRef<SILValue> args, As... baseArgs)
: Base(kind, DebugLoc, baseArgs...), SubstCalleeType(substCalleeType),
NumSubstitutions(substitutions.size()), NonThrowing(false),
Operands(this, args, callee) {
static_assert(sizeof(Impl) == sizeof(*this),
"subclass has extra storage, cannot use TailAllocatedOperandList");
memcpy(getSubstitutionsStorage(), substitutions.begin(),
sizeof(substitutions[0]) * substitutions.size());
}
static void *allocate(SILFunction &F,
ArrayRef<Substitution> substitutions,
ArrayRef<SILValue> args) {
return allocateApplyInst(F,
sizeof(Impl) +
decltype(Operands)::getExtraSize(args.size()) +
sizeof(substitutions[0]) * substitutions.size(),
alignof(Impl));
}
void setNonThrowing(bool isNonThrowing) { NonThrowing = isNonThrowing; }
bool isNonThrowingApply() const { return NonThrowing; }
public:
// The operand number of the first argument.
static unsigned getArgumentOperandNumber() { return 1; }
SILValue getCallee() const { return Operands[Callee].get(); }
// Gets the referenced function if the callee is a function_ref instruction.
SILFunction *getCalleeFunction() const {
if (auto *FRI = dyn_cast<FunctionRefInst>(getCallee()))
return FRI->getReferencedFunction();
return nullptr;
}
// Get the type of the callee without the applied substitutions.
CanSILFunctionType getOrigCalleeType() const {
return getCallee().getType().template castTo<SILFunctionType>();
}
// Get the type of the callee with the applied substitutions.
CanSILFunctionType getSubstCalleeType() const {
return SubstCalleeType.castTo<SILFunctionType>();
}
SILType getSubstCalleeSILType() const {
return SubstCalleeType;
}
SILResultInfo getSubstCalleeResultInfo() const {
return getSubstCalleeType()->getResult();
}
bool hasResultConvention(ResultConvention Conv) const {
return getSubstCalleeResultInfo().getConvention() == Conv;
}
bool isCalleeThin() const {
auto Rep = getSubstCalleeType()->getRepresentation();
return Rep == FunctionType::Representation::Thin;
}
/// True if this application has generic substitutions.
bool hasSubstitutions() const { return NumSubstitutions != 0; }
/// The substitutions used to bind the generic arguments of this function.
MutableArrayRef<Substitution> getSubstitutions() {
return {getSubstitutionsStorage(), NumSubstitutions};
}
ArrayRef<Substitution> getSubstitutions() const {
return {getSubstitutionsStorage(), NumSubstitutions};
}
/// The arguments passed to this instruction.
MutableArrayRef<Operand> getArgumentOperands() {
return Operands.getDynamicAsArray();
}
ArrayRef<Operand> getArgumentOperands() const {
return Operands.getDynamicAsArray();
}
/// The arguments passed to this instruction.
OperandValueArrayRef getArguments() const {
return Operands.getDynamicValuesAsArray();
}
/// Returns the number of arguments for this partial apply.
unsigned getNumArguments() const { return getArguments().size(); }
Operand &getArgumentRef(unsigned i) {
return Operands.getDynamicAsArray()[i];
}
/// Return the ith argument passed to this instruction.
SILValue getArgument(unsigned i) const { return getArguments()[i]; }
// Set the ith argument of this instruction.
void setArgument(unsigned i, SILValue V) {
return getArgumentOperands()[i].set(V);
}
ArrayRef<Operand> getAllOperands() const { return Operands.asArray(); }
MutableArrayRef<Operand> getAllOperands() { return Operands.asArray(); }
};
/// Given the callee operand of an apply or try_apply instruction,
/// does it have the given semantics?
bool doesApplyCalleeHaveSemantics(SILValue callee, StringRef semantics);
// The partial specialization of ApplyInstBase for full applications.
// Adds some methods relating to 'self' and to result types that don't
// make sense for partial applications.
template <class Impl, class Base>
class ApplyInstBase<Impl, Base, true>
: public ApplyInstBase<Impl, Base, false> {
using super = ApplyInstBase<Impl, Base, false>;
protected:
template <class... As>
ApplyInstBase(As &&...args)
: ApplyInstBase<Impl,Base,false>(std::forward<As>(args)...) {}
public:
using super::getCallee;
using super::getSubstCalleeType;
using super::hasSubstitutions;
using super::getSubstitutions;
using super::getNumArguments;
using super::getArgument;
using super::getArguments;
using super::getArgumentOperands;
/// The collection of following routines wrap the representation difference in
/// between the self substitution being first, but the self parameter of a
/// function being last.
///
/// The hope is that this will prevent any future bugs from coming up related
/// to this.
///
/// Self is always the last parameter, but self subtitutions are always
/// first. The reason to add this method is to wrap that dichotomy to reduce
/// errors.
///
/// FIXME: Could this be standardized? It has and will lead to bugs. IMHO.
SILValue getSelfArgument() const {
assert(hasSelfArgument() && "Must have a self argument");
assert(getNumArguments() && "Should only be called when Callee has "
"arguments.");
return getArgument(getNumArguments()-1);
}
Operand &getSelfArgumentOperand() {
assert(hasSelfArgument() && "Must have a self argument");
assert(getNumArguments() && "Should only be called when Callee has "
"arguments.");
return getArgumentOperands()[getNumArguments()-1];
}
void setSelfArgument(SILValue V) {
assert(hasSelfArgument() && "Must have a self argument");
assert(getNumArguments() && "Should only be called when Callee has "
"arguments.");
getArgumentOperands()[getNumArguments() - 1].set(V);
}
OperandValueArrayRef getArgumentsWithoutSelf() const {
assert(hasSelfArgument() && "Must have a self argument");
assert(getNumArguments() && "Should only be called when Callee has "
"at least a self parameter.");
assert(hasSubstitutions() && "Should only be called when Callee has "
"substitutions.");
ArrayRef<Operand> ops = this->getArgumentOperands();
ArrayRef<Operand> opsWithoutSelf = ArrayRef<Operand>(&ops[0],
ops.size()-1);
return OperandValueArrayRef(opsWithoutSelf);
}
Substitution getSelfSubstitution() const {
assert(getNumArguments() && "Should only be called when Callee has "
"at least a self parameter.");
assert(hasSubstitutions() && "Should only be called when Callee has "
"substitutions.");
return getSubstitutions()[0];
}
ArrayRef<Substitution> getSubstitutionsWithoutSelfSubstitution() const {
assert(getNumArguments() && "Should only be called when Callee has "
"at least a self parameter.");
assert(hasSubstitutions() && "Should only be called when Callee has "
"substitutions.");
return getSubstitutions().slice(1);
}
bool hasIndirectResult() const {
return getSubstCalleeType()->hasIndirectResult();
}
bool hasSelfArgument() const {
return getSubstCalleeType()->hasSelfParam();
}
bool hasGuaranteedSelfArgument() const {
auto C = getSubstCalleeType()->getSelfParameter().getConvention();
return C == ParameterConvention::Direct_Guaranteed;
}
SILValue getIndirectResult() const {
assert(hasIndirectResult() && "apply inst does not have indirect result!");
return getArguments().front();
}
OperandValueArrayRef getArgumentsWithoutIndirectResult() const {
if (hasIndirectResult())
return getArguments().slice(1);
return getArguments();
}
bool hasSemantics(StringRef semanticsString) const {
return doesApplyCalleeHaveSemantics(getCallee(), semanticsString);
}
};
/// ApplyInst - Represents the full application of a function value.
class ApplyInst : public ApplyInstBase<ApplyInst, SILInstruction> {
friend class SILBuilder;
ApplyInst(SILDebugLocation *DebugLoc, SILValue Callee,
SILType SubstCalleeType, SILType ReturnType,
ArrayRef<Substitution> Substitutions, ArrayRef<SILValue> Args,
bool isNonThrowing);
static ApplyInst *create(SILDebugLocation *DebugLoc, SILValue Callee,
SILType SubstCalleeType, SILType ReturnType,
ArrayRef<Substitution> Substitutions,
ArrayRef<SILValue> Args, bool isNonThrowing,
SILFunction &F);
public:
/// getType() is ok since this is known to only have one type.
SILType getType(unsigned i = 0) const { return ValueBase::getType(i); }
static bool classof(const ValueBase *V) {
return V->getKind() == ValueKind::ApplyInst;
}
/// Returns true if the called function has an error result but is not actully
/// throwing an error.
bool isNonThrowing() const {
return isNonThrowingApply();
}
};
/// PartialApplyInst - Represents the creation of a closure object by partial
/// application of a function value.
class PartialApplyInst
: public ApplyInstBase<PartialApplyInst, SILInstruction> {
friend class SILBuilder;
PartialApplyInst(SILDebugLocation *DebugLoc, SILValue Callee,
SILType SubstCalleeType,
ArrayRef<Substitution> Substitutions,
ArrayRef<SILValue> Args, SILType ClosureType);
static PartialApplyInst *create(SILDebugLocation *DebugLoc, SILValue Callee,
SILType SubstCalleeType,
ArrayRef<Substitution> Substitutions,
ArrayRef<SILValue> Args, SILType ClosureType,
SILFunction &F);
public:
/// getType() is ok since this is known to only have one type.
SILType getType(unsigned i = 0) const { return ValueBase::getType(i); }
/// Return the ast level function type of this partial apply.
CanSILFunctionType getFunctionType() const {
return getType().castTo<SILFunctionType>();
}
static bool classof(const ValueBase *V) {
return V->getKind() == ValueKind::PartialApplyInst;
}
};
//===----------------------------------------------------------------------===//
// Literal instructions.
//===----------------------------------------------------------------------===//
/// Abstract base class for literal instructions.
class LiteralInst : public SILInstruction {
protected:
LiteralInst(ValueKind Kind, SILDebugLocation *DebugLoc, SILType Ty)
: SILInstruction(Kind, DebugLoc, Ty) {}
public:
static bool classof(const ValueBase *V) {
return V->getKind() >= ValueKind::First_LiteralInst &&
V->getKind() <= ValueKind::Last_LiteralInst;
}
};
/// FunctionRefInst - Represents a reference to a SIL function.
class FunctionRefInst : public LiteralInst {
friend class SILBuilder;
SILFunction *Function;
/// Construct a FunctionRefInst.
///
/// \param DebugLoc The location of the reference.
/// \param F The function being referenced.
FunctionRefInst(SILDebugLocation *DebugLoc, SILFunction *F);
public:
~FunctionRefInst();
/// Return the referenced function.
SILFunction *getReferencedFunction() const { return Function; }
void dropReferencedFunction();
/// getType() is ok since this is known to only have one type.
/// The type is always a lowered function type.
SILType getType(unsigned i = 0) const { return ValueBase::getType(i); }
CanSILFunctionType getFunctionType() const {
return getType().castTo<SILFunctionType>();
}
ArrayRef<Operand> getAllOperands() const { return {}; }
MutableArrayRef<Operand> getAllOperands() { return {}; }
static bool classof(const ValueBase *V) {
return V->getKind() == ValueKind::FunctionRefInst;
}
};
/// Represents an invocation of builtin functionality provided by the code
/// generator.
class BuiltinInst : public SILInstruction {
friend class SILBuilder;
/// The name of the builtin to invoke.
Identifier Name;
/// The number of tail-allocated substitutions, allocated after the operand
/// list's tail allocation.
unsigned NumSubstitutions;
/// The value arguments to the builtin.
TailAllocatedOperandList<0> Operands;
Substitution *getSubstitutionsStorage() {
return reinterpret_cast<Substitution*>(Operands.asArray().end());
}
const Substitution *getSubstitutionsStorage() const {
return reinterpret_cast<const Substitution*>(Operands.asArray().end());
}
BuiltinInst(SILDebugLocation *DebugLoc, Identifier Name, SILType ReturnType,
ArrayRef<Substitution> Substitutions, ArrayRef<SILValue> Args);
static BuiltinInst *create(SILDebugLocation *DebugLoc, Identifier Name,
SILType ReturnType,
ArrayRef<Substitution> Substitutions,
ArrayRef<SILValue> Args, SILFunction &F);
public:
/// Return the name of the builtin operation.
Identifier getName() const { return Name; }
void setName(Identifier I) { Name = I; }
/// Currently all builtins have one result, so getType() is OK.
/// We may want to change that eventually.
SILType getType(unsigned i = 0) const { return ValueBase::getType(i); }
/// \brief Looks up the llvm intrinsic ID and type for the builtin function.
///
/// \returns Returns llvm::Intrinsic::not_intrinsic if the function is not an
/// intrinsic. The particular intrinsic functions which correspond to the
/// returned value are defined in llvm/Intrinsics.h.
const IntrinsicInfo &getIntrinsicInfo() const;
/// \brief Looks up the lazily cached identification for the builtin function.
const BuiltinInfo &getBuiltinInfo() const;
/// \brief Looks up the llvm intrinsic ID of this builtin. Returns None if
/// this is not an intrinsic.
llvm::Optional<llvm::Intrinsic::ID> getIntrinsicID() const {
auto I = getIntrinsicInfo();
if (I.ID == llvm::Intrinsic::not_intrinsic)
return None;
return I.ID;
}
/// \brief Looks up the BuiltinKind of this builtin. Returns None if this is
/// not a builtin.
llvm::Optional<BuiltinValueKind> getBuiltinKind() const {
auto I = getBuiltinInfo();
if (I.ID == BuiltinValueKind::None)
return None;
return I.ID;
}
/// True if this builtin application has substitutions, which represent type
/// parameters to the builtin.
bool hasSubstitutions() const {
return NumSubstitutions != 0;
}
/// Return the type parameters to the builtin.