Commit Graph

108 Commits

Author SHA1 Message Date
Doug Gregor
43df05a89c [SE-0470] Prohibit isolated conformances in dynamic casts marked as such
Certain dynamic casts cannot work safely with isolated conformances,
regardless of what executor the code runs on. For such cases, reject
all attempts to conform to the type.
2025-03-26 22:31:52 -07:00
Slava Pestov
0c2f28fd3d AST: Remove GenericSignature parameter from OpenedArchetypeType::get() 2024-08-20 12:15:27 -04:00
Tim Kientzle
1d961ba22d Add #include "swift/Basic/Assertions.h" to a lot of source files
Although I don't plan to bring over new assertions wholesale
into the current qualification branch, it's entirely possible
that various minor changes in main will use the new assertions;
having this basic support in the release branch will simplify that.
(This is why I'm adding the includes as a separate pass from
rewriting the individual assertions)
2024-06-05 19:37:30 -07:00
Ben Barham
f292ec9784 Use the new template deduction guides rather than makeArrayRef
LLVM has removed `make*ArrayRef`, migrate all references to their
constructor equivalent.
2024-02-23 20:04:51 -08:00
Ben Barham
ef8825bfe6 Migrate llvm::Optional to std::optional
LLVM has removed llvm::Optional, move over to std::optional. Also
clang-format to fix up all the renamed #includes.
2024-02-21 11:20:06 -08:00
Nate Chandler
1875361efe [IRGen] Added dominance scope. 2023-07-27 15:05:49 -07:00
Nate Chandler
e5d87f75a8 [SIL] Add source formal type to checked_cast_br.
It is necessary for opaque values where for casts that will newly start
out as checked_cast_brs and be lowered to checked_cast_addr_brs, since
the latter has the source formal type, IRGen relies on being able to
access it, and there's no way in general to obtain the source formal
type from the source lowered type.
2023-07-27 15:04:15 -07:00
Evan Wilde
250082df25 [NFC] Reformat all the LLVMs
Reformatting everything now that we have `llvm` namespaces. I've
separated this from the main commit to help manage merge-conflicts and
for making it a bit easier to read the mega-patch.
2023-06-27 09:03:52 -07:00
Evan Wilde
f3ff561c6f [NFC] add llvm namespace to Optional and None
This is phase-1 of switching from llvm::Optional to std::optional in the
next rebranch. llvm::Optional was removed from upstream LLVM, so we need
to migrate off rather soon. On Darwin, std::optional, and llvm::Optional
have the same layout, so we don't need to be as concerned about ABI
beyond the name mangling. `llvm::Optional` is only returned from one
function in
```
getStandardTypeSubst(StringRef TypeName,
                     bool allowConcurrencyManglings);
```
It's the return value, so it should not impact the mangling of the
function, and the layout is the same as `std::optional`, so it should be
mostly okay. This function doesn't appear to have users, and the ABI was
already broken 2 years ago for concurrency and no one seemed to notice
so this should be "okay".

I'm doing the migration incrementally so that folks working on main can
cherry-pick back to the release/5.9 branch. Once 5.9 is done and locked
away, then we can go through and finish the replacement. Since `None`
and `Optional` show up in contexts where they are not `llvm::None` and
`llvm::Optional`, I'm preparing the work now by going through and
removing the namespace unwrapping and making the `llvm` namespace
explicit. This should make it fairly mechanical to go through and
replace llvm::Optional with std::optional, and llvm::None with
std::nullopt. It's also a change that can be brought onto the
release/5.9 with minimal impact. This should be an NFC change.
2023-06-27 09:03:52 -07:00
Nate Chandler
70cfa6a05c [IRGen] Check for nil in final class cast opt.
As an optimization, there is a fast-cast to non-final classes that just
compares isa pointers.  If the source of the cast is an Optional<class>,
though, it's not allowed to "directly compare the isa-pointer"; because
the source might be Optional.none, i.e. null.

Add a check for nil when emitting the fast class cast.

rdar://108614878
2023-05-03 18:39:08 -07:00
Arnold Schwaighofer
3905955589 Merge pull request #61232 from aschwaighofer/wip_opaque_ptr_2
IRGen: Pass the elementType of pointers through to operations
2022-10-04 10:56:41 -07:00
Arnold Schwaighofer
d810b0f7e4 IRGen: Pass the elementType of pointers through to operations
In preparation for moving to llvm's opaque pointer representation
replace getPointerElementType and CreateCall/CreateLoad/Store uses that
dependent on the address operand's pointer element type.

This means an `Address` carries the element type and we use
`FunctionPointer` in more places or read the function type off the
`llvm::Function`.
2022-10-03 15:27:12 -07:00
Erik Eckstein
2527d3765e IRGen: fix how metadata is loaded for fast class casting
Pass the correct type to `emitHeapMetadataRefForHeapObject()`.
Fixes a runtime crash in case a class protocol is cast to a final swift class, where the actual object is an ObjectiveC class instance.

rdar://99626888
2022-09-22 08:46:18 +02:00
Slava Pestov
c80d8e6b1c IRGen: Exclude classes defined in generic contexts from fast cast optimization
This is a regression from https://github.com/apple/swift/pull/41784.

Fixes rdar://problem/93822961.
2022-07-12 04:11:32 -04:00
Robert Widmann
c06e811b09 Fixup Extended Existential Metatype Casts
The fix here is two-fold:

1) Teach SILGen that it cannot use the scalar casting paths for extended existentials
2) Teach the runtime casting entrypoint to unwrap as much metatype structure as possible
   before arriving at a 'Self' type bound for the requirement checking paths.

The code here mirrors the destructuring check we're doing in remote mirrors.

rdar://95166916
2022-06-16 14:35:20 -06:00
Josh Soref
9fa14ca215 Spelling irgen (#42470)
* spelling: abstractable

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: across

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: clazz

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: command

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: components

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: current

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: declared

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: discrimination

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: entities

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: except

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: existential

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: generic

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: initialization

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: initialize

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: inserted

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: instantiate

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: instantiation

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: interfere

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: interferes

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: intrinsic

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: metadata

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: might

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: multiple

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: necessary

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: objective

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: occurrences

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: outlined

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: parameters

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: payload

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: rearchitecting

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: replaceable

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: reverse

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: rewritable

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: shareably

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: specializations

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: speedup

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: template

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: that

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: the

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: transferred

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: uninitialized

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: witness

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

Co-authored-by: Josh Soref <jsoref@users.noreply.github.com>
2022-04-21 14:02:03 -07:00
John McCall
5519749ade [NFC] Collect protocol decls, not type, in ExistentialLayout
Another thing that will be necessary for correctness with
compositions of parameterized protocols.
2022-04-11 22:15:16 -04:00
Saleem Abdulrasool
52d39f85f8 IRGen: enable the dynamic cast optimization on Windows
This accommodates lazy initialization of class metadata for the dynamic
cast elision optimization.  In the case of a lazy initialization, we
cannot assume that we are able to directly access the metadata through
a GEP, instead we should go through the type metadata accessor.
Although this is a slight bit more expensive, the hot-path of this is
roughly a function call + pointer check (if the value is in the cache,
we just return, otherwise we will have to initialize the type metadata
the first time around).

Special thanks to @atrick for the discussion, pointers, and general help
with trying to enable this optimization!
2022-04-10 09:56:28 -07:00
Erik Eckstein
860078a79a IRGen: fast casting to final classes
When casting a class instance to a final class, we can directly compare the isa-pointer with address of the metadata.
This avoids a call to `swift_dynamicCastClass`.
It also avoids a call to the metadata accessor of the class (which calls `swift_getInitializedObjCClass`).
For comparing the metadata pointers it's not required that the metadata is fully initialized.
2022-04-07 16:36:21 +02:00
Robert Widmann
f694bf585b Plumb GenericSignature of SIL Function Through IRGen 2022-03-08 03:09:19 -08:00
tbkka
b0675c0dd6 [DynamicCast] Rely on runtime when casts can't be optimized (#33761)
* [DynamicCast] Rely on runtime when casts can't be optimized

The Swift compiler renders `as?` operations in Swift into variations of the
`checked_cast_br` instructions in SIL.  Subsequent optimization passes may alter
or eliminate these instructions.  Any remaining instructions after optimization
are translated by IRGen into runtime calls.

At least, that's the theory.  Unfortunately, the current IRGen logic does not
recognize all of the casting instruction variants and renders one particular
unrecognized variant as a simple nil load.  Specifically, this occurs for
optimized casts of metatypes to AnyObject:
```
  let a = Int.self
  let b = a as? AnyObject
  // b should not be nil here
```

This PR changes this case in IRGen to instead generate a call to
`swift_dynamicCast`, deferring this case to the runtime.

Future:  Someday, the compiler should be taught to correctly optimize
this cast away.
2020-10-28 15:59:13 -07:00
John McCall
03d94b44a6 Add default IR attributes to helper functions and convert
several more places to use getOrCreateHelperFunction.

This means that several of these places are now emitting
shared functions rather than private ones, which I've
verified is okay.  There are some other places where
privacy is still unfortunately necessary.

I've also fixed the name of the store-extra-inhabitants
helper function to say "store" instead of "get", which
is longstanding (but harmless because it's private).

Fixes rdar://66707994.
2020-08-08 16:57:02 -04:00
Slava Pestov
c8da1583cf IRGen: Correctly use formal type for class downcasts
Fixes <https://bugs.swift.org/browse/SR-11818>, <rdar://problem/57369535>.
2019-11-22 16:39:17 -05:00
Arnold Schwaighofer
e4e162d25f IRGen: Fix cast of existential type with anyobject to super class constraint existential
rdar://55987397
SR-11565
2019-10-11 10:00:14 -07:00
Erik Eckstein
ffd7f75de3 IRGen: debug info generation for cond_fail messages.
To display a failure message in the debugger, create a function in the debug info which has the name of the failure message.
The debug location of the trap/cond_fail is then wrapped into this function and the function is declared as "inlined".
In case the debugger stops at the trap instruction, it displays the inline function, which looks like the failure message.
For example:

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
    frame #0: 0x0000000100000cbf a.out`testit3(_:) [inlined] Unexpectedly found nil while unwrapping an Optional value at test.swift:14:11 [opt]
   11
   12   @inline(never)
   13   func testit(_ a: Int?) -> Int {
-> 14     return a!
   15   }
   16

This change is currently not enabled by default, but can be enabled with the option "-Xllvm -enable-trap-debug-info".
Enabling this feature needs some changes in lldb. When the lldb part is done, this option can be removed and the feature enabled by default.
2019-07-16 14:51:18 +02:00
Brent Royal-Gordon
d5a2912a26 Revert "Better runtime failure messages (not yet enabled by default)" 2019-07-15 13:42:40 -07:00
Erik Eckstein
e915300e96 IRGen: debug info generation for cond_fail messages.
To display a failure message in the debugger, create a function in the debug info which has the name of the failure message.
The debug location of the trap/cond_fail is then wrapped into this function and the function is declared as "inlined".
In case the debugger stops at the trap instruction, it displays the inline function, which looks like the failure message.
For example:

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
    frame #0: 0x0000000100000cbf a.out`testit3(_:) [inlined] Unexpectedly found nil while unwrapping an Optional value at test.swift:14:11 [opt]
   11
   12   @inline(never)
   13   func testit(_ a: Int?) -> Int {
-> 14     return a!
   15   }
   16

This change is currently not enabled by default, but can be enabled with the option "-Xllvm -enable-trap-debug-info".
Enabling this feature needs some changes in lldb. When the lldb part is done, this option can be removed and the feature enabled by default.
2019-07-12 14:03:13 +02:00
Saleem Abdulrasool
731c31f9a5 MSVC: litter the code with llvm_unreachable (NFC)
Add `llvm_unreachable` to mark covered switches which MSVC does not
analyze correctly and believes that there exists a path through the
function without a return value.
2019-06-01 19:02:46 -07:00
Slava Pestov
d6868acf8a IRGen: Categories on class stubs should go in a separate list and section 2019-04-19 16:50:29 -04:00
Slava Pestov
68c07620cd IRGen: Emit Objective-C resilient class stubs if experimental flag is on
Non-generic classes with resilient ancestry do not have statically-emitted
metadata, so we can now emit an Objective-C resilient class stub instead.

Also, when emitting an Objective-C category, reference the class stub if
the class has resilient ancestry; previously this case would hit an assert.

Note that class stubs always start with a zero word, with the address point
pointing immediately after. This works around a linker issue, where the
linker tries to coalesce categories and gets confused upon encountering a
class stub.
2019-03-26 18:53:09 -04:00
Joe Groff
bce1f5ef4a Runtime: Provide ABI space for source location info in unconditional casts.
Currently ignored, but this will allow future compilers to pass down source location information for cast
failure runtime errors without backward deployment constraints.
2018-12-06 14:58:14 -08:00
Doug Gregor
bec722df57 [Runtime/IRGen] Switch swift_getExistentialTypeMetadata() to ProtocolDescriptorRef.
Switch one entry point in the runtime (swift_getExistentialTypeMetadata)
to use ProtocolDescriptorRef rather than a protocol descriptor. Update
IRGen to produce ProtocolDescriptorRef instances for its calls, setting
the discriminator bit appropriately.

Within the runtime, verify that all instances of ProtocolDescriptorRef have
the right layout, i.e., the discriminator bit is set for @objc protocols
but not Swift protocols.
2018-07-21 07:48:34 -07:00
Slava Pestov
01a27ed75b IRGen: Tweak dynamic casting for protocols with superclasses 2018-07-09 23:56:25 -07:00
Slava Pestov
45fb11ce3c AST: Add ExistentialLayout::getSuperclass(), rename superclass to explicitSuperclass
More groundwork for protocols with superclass constraints.
In several places we need to distinguish between existential
types that have a superclass term (MyClass & Proto) and
existential types containing a protocol with a superclass
constraint.

This is similar to how I can write 'AnyObject & Proto', or
write 'Proto1 & Proto2' where Proto1 has an ': AnyObject'
in its inheritance clause.

Note that some of the usages will be revisited later as
I do more refactoring and testing. This is just a first pass.
2018-07-02 22:06:33 -07:00
David Zarzycki
8c0c55539f [SIL] NFC: Rename misleading getSwiftRValueType() to getASTType()
Reference storage types are not RValues. Also, use more SILType helper
methods to avoid line wrap.
2018-05-04 08:14:38 -04:00
Joe Groff
a4aa054838 IRGen: Make type(of:) behavior consistent in ObjC bridged contexts.
When we use type(of: x) on a class in an ObjC bridged context, the optimizer turns this into a SIL `value_metatype @objc` operation, which is supposed to get the dynamic type of the object as an ObjC class. This was previously lowered by IRGen into a `object_getClass` call, which extracts the isa pointer from the object, but is inconsistent with the `-class` method in ObjC or with the Swift-native behavior, which both look through artificial subclasses, proxies, and so on. This inconsistency led to observably different behavior between debug and release builds and between ObjC-bridged and native entry points, so provide an alternative runtime entry point that replicates the behavior of getting a native Swift class. Fixes SR-7258.
2018-04-06 15:17:04 -07:00
Arnold Schwaighofer
0f8548153f IRGen: Add nil checks to scalarCheckedCasts
We claim to handle optional input types but not all paths of this function actually do.

rdar://39195672
2018-04-05 13:04:27 -07:00
Arnold Schwaighofer
760f773ed5 IRGen: Exact casts cannot fail
Use initialized metadata in exact checks otherwise we will fail in
[exact] checks when we shouldn't.

rdar://38885852
2018-04-03 15:19:38 -07:00
John McCall
a906f43329 Allow type metadata to be incomplete.
Most of the work of this patch is just propagating metadata states
throughout the system, especially local-type-data caching and
metadata-path resolution.  It took a few design revisions to get both
DynamicMetadataRequest and MetadataResponse to a shape that felt
right and seemed to make everything easier.

The design is laid out pretty clearly (I hope) in the comments on
DynamicMetadataRequest and MetadataResponse, so I'm not going to
belabor it again here.  Instead, I'll list out the work that's still
outstanding:

- I'm sure there are places we're asking for complete metadata where
  we could be asking for something weaker.

- I need to actually test the runtime behavior to verify that it's
  breaking the cycles it's supposed to, instead of just not regressing
  anything else.

- I need to add something to the runtime to actually force all the
  generic arguments of a generic type to be complete before reporting
  completion.  I think we can get away with this for now because all
  existing types construct themselves completely on the first request,
  but there might be a race condition there if another asks for the
  type argument, gets an abstract metadata, and constructs a type with
  it without ever needing it to be completed.

- Non-generic resilient types need to be switched over to an IRGen
  pattern that supports initialization suspension.

- We should probably space out the MetadataStates so that there's some
  space between Abstract and Complete.

- The runtime just calmly sits there, never making progress and
  permanently blocking any waiting threads, if you actually form an
  unresolvable metadata dependency cycle.  It is possible to set up such
  a thing in a way that Sema can't diagnose, and we should detect it at
  runtime.  I've set up some infrastructure so that it should be
  straightforward to diagnose this, but I haven't actually implemented
  the diagnostic yet.

- It's not clear to me that swift_checkMetadataState is really cheap
  enough that it doesn't make sense to use a cache for type-fulfilled
  metadata in associated type access functions.  Fortunately this is not
  ABI-affecting, so we can evaluate it anytime.

- Type layout really seems like a lot of code now that we sometimes
  need to call swift_checkMetadataState for generic arguments.  Maybe
  we can have the runtime do this by marking low bits or something, so
  that a TypeLayoutRef is actually either (1) a TypeLayout, (2) a known
  layout-complete metadata, or (3) a metadata of unknown state.  We could
  do that later with a flag, but we'll need to at least future-proof by
  allowing the runtime functions to return a MetadataDependency.
2018-03-26 12:18:04 -04:00
John McCall
aaa40ee82b Move metadata-accessing IRGen out of GenMeta. NFC.
Abstract type/heap metadata access goes into MetadataRequest.
Metadata access starting from a heap object goes into GenHeap.
Accessing various components of class metadata goes into GenClass
or MetadataLayout.
2018-03-18 23:53:11 -04:00
Vedant Kumar
132bb19274 [IRGen] Avoid generating mergeable traps
Factor out and reuse logic in the lowering of CondFailInst to emit
non-mergeable traps, everywhere we emit traps. This should address a
debugging quality issue with ambiguous ud2 instructions.

rdar://32772768
2018-02-20 13:40:40 -08:00
Mark Lacey
b4b66bc8e8 Replace getAnyOptionalObjectType with getOptionalObjectType. 2018-02-05 23:59:00 -08:00
John McCall
a0f20f673d Switch all of the indirect-call code in IRGen to FunctionPointer.
To make this stick, I've disallowed direct use of that overload of
CreateCall.  I've left the Constant overloads available, but eventually
we might want to consider fixing those, too, just to get all of this
code out of the business of manually remembering to pass around
attributes and calling conventions.

The test changes reflect the fact that we weren't really setting
attributes consistently at all, in this case on value witnesses.
2017-07-28 23:26:35 -04:00
Slava Pestov
b5721e8d8e AST: Remove AnyObject protocol 2017-05-02 19:45:00 -07:00
Slava Pestov
4fd870b81d AST: Change ExistentialLayout::requiresClass from a field to a method
We need to compute it lazily to avoid calling
ProtocolDecl::requiresClass() before the protocol's
inheritance clause has been type checked.
2017-05-01 15:49:03 -07:00
Slava Pestov
454495f974 IRGen: Subclass existential scalar downcasts
This handles the case where the left hand side of the cast is known
to be class-like, and the right hand side is known at compile time
to be a protocol composition type.

Note that this change results in a small optimization -- a checked
cast of a metatype known to be a class metatype to a class-constrained
existential metatype no longer has to emit an explicit check that
the source is class-constrained.

Fully dynamic casts are coming up next.
2017-04-25 02:42:14 -07:00
Slava Pestov
7bf2f7d6fc IRGen: Start using ExistentialLayout
Replace a few usages of TypeBase::getExistentialTypeProtocols(),
which I'm going to remove.

NFC for now, since subclass existentials are still not fully
plumbed through here.
2017-04-13 21:29:57 -07:00
Slava Pestov
d58f049608 AST: Introduce ASTContext::getAnyObjectType()
This replaces a number of usages of KnownProtocolKind::AnyObject,
which is soon going away.
2017-04-13 21:17:05 -07:00
Slava Pestov
83ca7a852f AST: Remove TypeBase::getClassBound() 2017-02-27 20:00:36 -08:00
Hugh Bellamy
f001b7562b Use relatively new LLVM_FALLLTHROUGH instead of our own SWIFT_FALLTHROUGH 2017-02-12 10:47:03 +07:00