@@ -109,6 +109,76 @@ Solution::computeSubstitutions(GenericSignature sig,
109109 lookupConformanceFn);
110110}
111111
112+ // On Windows and 32-bit platforms we need to force "Int" to actually be
113+ // re-imported as "Int." This is needed because otherwise, we cannot round-trip
114+ // "Int" and "UInt". For example, on Windows, "Int" will be imported into C++ as
115+ // "long long" and then back into Swift as "Int64" not "Int."
116+ static ValueDecl *rewriteIntegerTypes (SubstitutionMap subst, ValueDecl *oldDecl,
117+ AbstractFunctionDecl *newDecl) {
118+ auto originalFnSubst = cast<AbstractFunctionDecl>(oldDecl)
119+ ->getInterfaceType ()
120+ ->getAs <GenericFunctionType>()
121+ ->substGenericArgs (subst);
122+ // The constructor type is a function type as follows:
123+ // (CType.Type) -> (Generic) -> CType
124+ // And a method's function type is as follows:
125+ // (inout CType) -> (Generic) -> Void
126+ // In either case, we only want the result of that function type because that
127+ // is the function type with the generic params that need to be substituted:
128+ // (Generic) -> CType
129+ if (isa<ConstructorDecl>(oldDecl) || oldDecl->isInstanceMember () ||
130+ oldDecl->isStatic ())
131+ originalFnSubst = cast<FunctionType>(originalFnSubst->getResult ().getPointer ());
132+
133+ SmallVector<ParamDecl *, 4 > fixedParameters;
134+ unsigned parameterIndex = 0 ;
135+ for (auto *newFnParam : *newDecl->getParameters ()) {
136+ // If the user substituted this param with an (U)Int, use (U)Int.
137+ auto substParamType =
138+ originalFnSubst->getParams ()[parameterIndex].getParameterType ();
139+ if (substParamType->isEqual (newDecl->getASTContext ().getIntType ()) ||
140+ substParamType->isEqual (newDecl->getASTContext ().getUIntType ())) {
141+ auto intParam =
142+ ParamDecl::cloneWithoutType (newDecl->getASTContext (), newFnParam);
143+ intParam->setInterfaceType (substParamType);
144+ fixedParameters.push_back (intParam);
145+ } else {
146+ fixedParameters.push_back (newFnParam);
147+ }
148+ parameterIndex++;
149+ }
150+
151+ auto fixedParams =
152+ ParameterList::create (newDecl->getASTContext (), fixedParameters);
153+ newDecl->setParameters (fixedParams);
154+
155+ // Now fix the result type:
156+ if (originalFnSubst->getResult ()->isEqual (
157+ newDecl->getASTContext ().getIntType ()) ||
158+ originalFnSubst->getResult ()->isEqual (
159+ newDecl->getASTContext ().getUIntType ())) {
160+ // Constructors don't have a result.
161+ if (auto func = dyn_cast<FuncDecl>(newDecl)) {
162+ // We have to rebuild the whole function.
163+ auto newFnDecl = FuncDecl::createImported (
164+ func->getASTContext (), func->getNameLoc (),
165+ func->getName (), func->getNameLoc (),
166+ func->hasAsync (), func->hasThrows (),
167+ fixedParams, originalFnSubst->getResult (),
168+ /* genericParams=*/ nullptr , func->getDeclContext (), newDecl->getClangDecl ());
169+ if (func->isStatic ()) newFnDecl->setStatic ();
170+ if (func->isImportAsStaticMember ()) newFnDecl->setImportAsStaticMember ();
171+ if (func->getImportAsMemberStatus ().isInstance ()) {
172+ newFnDecl->setSelfAccessKind (func->getSelfAccessKind ());
173+ newFnDecl->setSelfIndex (func->getSelfIndex ());
174+ }
175+ return newFnDecl;
176+ }
177+ }
178+
179+ return newDecl;
180+ }
181+
112182// Derive a concrete function type for fdecl by substituting the generic args
113183// and use that to derive the corresponding function type and parameter list.
114184static std::pair<FunctionType *, ParameterList *>
@@ -149,65 +219,6 @@ substituteFunctionTypeAndParamList(ASTContext &ctx, AbstractFunctionDecl *fdecl,
149219 return {newFnType, newParamList};
150220}
151221
152- static ValueDecl *generateSpecializedCXXFunctionTemplate (
153- ASTContext &ctx, AbstractFunctionDecl *oldDecl, SubstitutionMap subst,
154- clang::FunctionDecl *specialized) {
155- auto newFnTypeAndParams = substituteFunctionTypeAndParamList (ctx, oldDecl, subst);
156- auto newFnType = newFnTypeAndParams.first ;
157- auto paramList = newFnTypeAndParams.second ;
158-
159- SmallVector<ParamDecl *, 4 > newParamsWithoutMetatypes;
160- for (auto param : *paramList ) {
161- if (isa<FuncDecl>(oldDecl) &&
162- isa<MetatypeType>(param->getType ().getPointer ())) {
163- // Metatype parameters are added synthetically to account for template
164- // params that don't make it to the function signature. These shouldn't
165- // exist in the resulting specialized FuncDecl. Note that this doesn't
166- // affect constructors because all template params for a constructor
167- // must be in the function signature by design.
168- continue ;
169- }
170- newParamsWithoutMetatypes.push_back (param);
171- }
172- auto *newParamList =
173- ParameterList::create (ctx, SourceLoc (), newParamsWithoutMetatypes, SourceLoc ());
174-
175- if (isa<ConstructorDecl>(oldDecl)) {
176- DeclName ctorName (ctx, DeclBaseName::createConstructor (), newParamList);
177- auto newCtorDecl = ConstructorDecl::createImported (
178- ctx, specialized, ctorName, oldDecl->getLoc (),
179- /* failable=*/ false , /* failabilityLoc=*/ SourceLoc (),
180- /* Async=*/ false , /* AsyncLoc=*/ SourceLoc (),
181- /* throws=*/ false , /* throwsLoc=*/ SourceLoc (),
182- newParamList, /* genericParams=*/ nullptr ,
183- oldDecl->getDeclContext ());
184- return newCtorDecl;
185- }
186-
187- // Generate a name for the specialized function.
188- std::string newNameStr;
189- llvm::raw_string_ostream buffer (newNameStr);
190- std::unique_ptr<clang::MangleContext> mangler (
191- specialized->getASTContext ().createMangleContext ());
192- mangler->mangleName (specialized, buffer);
193- buffer.flush ();
194- // Add all parameters as empty parameters.
195- auto newName = DeclName (
196- ctx, DeclName (ctx.getIdentifier (newNameStr)).getBaseName (), newParamList);
197-
198- auto newFnDecl = FuncDecl::createImported (
199- ctx, oldDecl->getLoc (), newName, oldDecl->getNameLoc (),
200- /* Async=*/ false , oldDecl->hasThrows (), newParamList,
201- newFnType->getResult (), /* GenericParams=*/ nullptr ,
202- oldDecl->getDeclContext (), specialized);
203- if (oldDecl->isStatic ()) {
204- newFnDecl->setStatic ();
205- newFnDecl->setImportAsStaticMember ();
206- }
207- newFnDecl->setSelfAccessKind (cast<FuncDecl>(oldDecl)->getSelfAccessKind ());
208- return newFnDecl;
209- }
210-
211222// Synthesizes the body of a thunk that takes extra metatype arguments and
212223// skips over them to forward them along to the FuncDecl contained by context.
213224// This is used when importing a C++ templated function where the template params
@@ -249,20 +260,32 @@ synthesizeForwardingThunkBody(AbstractFunctionDecl *afd, void *context) {
249260 return {body, /* isTypeChecked=*/ true };
250261}
251262
252- ConcreteDeclRef
253- Solution::resolveConcreteDeclRef (ValueDecl *decl,
254- ConstraintLocator *locator) const {
255- if (!decl)
256- return ConcreteDeclRef ();
257-
258- // Get the generic signatue of the decl and compute the substitutions.
259- auto sig = decl->getInnermostDeclContext ()->getGenericSignatureOfContext ();
260- auto subst = computeSubstitutions (sig, locator);
263+ static ValueDecl *generateThunkForExtraMetatypes (SubstitutionMap subst,
264+ FuncDecl *oldDecl,
265+ FuncDecl *newDecl) {
266+ // We added additional metatype parameters to aid template
267+ // specialization, which are no longer now that we've specialized
268+ // this function. Create a thunk that only forwards the original
269+ // parameters along to the clang function.
270+ auto thunkTypeAndParamList = substituteFunctionTypeAndParamList (oldDecl->getASTContext (),
271+ oldDecl, subst);
272+ auto thunk = FuncDecl::createImplicit (
273+ oldDecl->getASTContext (), oldDecl->getStaticSpelling (), oldDecl->getName (),
274+ oldDecl->getNameLoc (), oldDecl->hasAsync (), oldDecl->hasThrows (),
275+ /* genericParams=*/ nullptr , thunkTypeAndParamList.second ,
276+ thunkTypeAndParamList.first ->getResult (), oldDecl->getDeclContext ());
277+ thunk->copyFormalAccessFrom (oldDecl);
278+ thunk->setBodySynthesizer (synthesizeForwardingThunkBody, newDecl);
279+ thunk->setSelfAccessKind (oldDecl->getSelfAccessKind ());
280+
281+ return thunk;
282+ }
261283
262- // Lazily instantiate function definitions for class template specializations.
263- // Members of a class template specialization will be instantiated here (not
264- // when imported). If this method has already be instantiated, then this is a
265- // no-op.
284+ // Lazily instantiate function definitions for class template specializations.
285+ // Members of a class template specialization will be instantiated here (not
286+ // when imported). If this method has already be instantiated, then this is a
287+ // no-op.
288+ static void maybeInstantiateCXXMethodDefinition (ValueDecl *decl) {
266289 if (const auto *constMethod =
267290 dyn_cast_or_null<clang::CXXMethodDecl>(decl->getClangDecl ())) {
268291 auto method = const_cast <clang::CXXMethodDecl *>(constMethod);
@@ -273,41 +296,62 @@ Solution::resolveConcreteDeclRef(ValueDecl *decl,
273296 ->getClangSema ()
274297 .InstantiateFunctionDefinition (method->getLocation (), method);
275298 }
299+ }
300+
301+ static ConcreteDeclRef getCXXFunctionTemplateSpecialization (SubstitutionMap subst,
302+ ValueDecl *decl) {
303+ assert (isa<clang::FunctionTemplateDecl>(decl->getClangDecl ()) &&
304+ " This API should only be used with function templates." );
305+
306+ auto *newFn =
307+ decl->getASTContext ()
308+ .getClangModuleLoader ()
309+ ->instantiateCXXFunctionTemplate (
310+ decl->getASTContext (),
311+ const_cast <clang::FunctionTemplateDecl *>(
312+ cast<clang::FunctionTemplateDecl>(decl->getClangDecl ())),
313+ subst);
314+ // We failed to specialize this function template. The compiler is going to
315+ // exit soon. Return something valid in the meantime.
316+ if (!newFn)
317+ return ConcreteDeclRef (decl);
318+
319+ auto newDecl = cast_or_null<ValueDecl>(
320+ decl->getASTContext ().getClangModuleLoader ()->importDeclDirectly (
321+ newFn));
322+
323+ if (auto fn = dyn_cast<AbstractFunctionDecl>(newDecl)) {
324+ if (!subst.empty ()) {
325+ newDecl = rewriteIntegerTypes (subst, decl, fn);
326+ }
327+ }
328+
329+ if (auto fn = dyn_cast<FuncDecl>(decl)) {
330+ if (newFn->getNumParams () != fn->getParameters ()->size ()) {
331+ newDecl = generateThunkForExtraMetatypes (subst, fn,
332+ cast<FuncDecl>(newDecl));
333+ }
334+ }
335+
336+ return ConcreteDeclRef (newDecl);
337+ }
338+
339+ ConcreteDeclRef
340+ Solution::resolveConcreteDeclRef (ValueDecl *decl,
341+ ConstraintLocator *locator) const {
342+ if (!decl)
343+ return ConcreteDeclRef ();
344+
345+ // Get the generic signatue of the decl and compute the substitutions.
346+ auto sig = decl->getInnermostDeclContext ()->getGenericSignatureOfContext ();
347+ auto subst = computeSubstitutions (sig, locator);
348+
349+ maybeInstantiateCXXMethodDefinition (decl);
276350
277351 // If this is a C++ function template, get it's specialization for the given
278352 // substitution map and update the decl accordingly.
279353 if (isa_and_nonnull<clang::FunctionTemplateDecl>(decl->getClangDecl ())) {
280- auto *newFn =
281- decl->getASTContext ()
282- .getClangModuleLoader ()
283- ->instantiateCXXFunctionTemplate (
284- decl->getASTContext (),
285- const_cast <clang::FunctionTemplateDecl *>(
286- cast<clang::FunctionTemplateDecl>(decl->getClangDecl ())),
287- subst);
288- auto newDecl = generateSpecializedCXXFunctionTemplate (
289- decl->getASTContext (), cast<AbstractFunctionDecl>(decl), subst, newFn);
290- if (auto fn = dyn_cast<FuncDecl>(decl)) {
291- if (newFn->getNumParams () != fn->getParameters ()->size ()) {
292- // We added additional metatype parameters to aid template
293- // specialization, which are no longer now that we've specialized
294- // this function. Create a thunk that only forwards the original
295- // parameters along to the clang function.
296- auto thunkTypeAndParamList = substituteFunctionTypeAndParamList (decl->getASTContext (),
297- fn, subst);
298- auto thunk = FuncDecl::createImplicit (
299- fn->getASTContext (), fn->getStaticSpelling (), fn->getName (),
300- fn->getNameLoc (), fn->hasAsync (), fn->hasThrows (),
301- /* genericParams=*/ nullptr , thunkTypeAndParamList.second ,
302- thunkTypeAndParamList.first ->getResult (), fn->getDeclContext ());
303- thunk->copyFormalAccessFrom (fn);
304- thunk->setBodySynthesizer (synthesizeForwardingThunkBody, cast<FuncDecl>(newDecl));
305- thunk->setSelfAccessKind (fn->getSelfAccessKind ());
306-
307- return ConcreteDeclRef (thunk);
308- }
309- }
310- return ConcreteDeclRef (newDecl);
354+ return getCXXFunctionTemplateSpecialization (subst, decl);
311355 }
312356
313357 return ConcreteDeclRef (decl, subst);
0 commit comments