Merge pull request #2448 from BrzVlad/feature-cprop-opt
[mono.git] / mcs / tools / linker / Mono.Linker.Steps / MarkStep.cs
1 //
2 // MarkStep.cs
3 //
4 // Author:
5 //   Jb Evain (jbevain@gmail.com)
6 //
7 // (C) 2006 Jb Evain
8 // (C) 2007 Novell, Inc.
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 //
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 //
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System;
31 using System.Collections;
32 using System.Linq;
33
34 using Mono.Cecil;
35 using Mono.Cecil.Cil;
36
37 namespace Mono.Linker.Steps {
38
39         public class MarkStep : IStep {
40
41                 protected LinkContext _context;
42                 protected Queue _methods;
43                 protected ArrayList _virtual_methods;
44
45                 public AnnotationStore Annotations {
46                         get { return _context.Annotations; }
47                 }
48
49                 public MarkStep ()
50                 {
51                         _methods = new Queue ();
52                         _virtual_methods = new ArrayList ();
53                 }
54
55                 public virtual void Process (LinkContext context)
56                 {
57                         _context = context;
58
59                         Initialize ();
60                         Process ();
61                 }
62
63                 void Initialize ()
64                 {
65                         foreach (AssemblyDefinition assembly in _context.GetAssemblies ())
66                                 InitializeAssembly (assembly);
67                 }
68
69                 protected virtual void InitializeAssembly (AssemblyDefinition assembly)
70                 {
71                         MarkAssembly (assembly);
72                         foreach (TypeDefinition type in assembly.MainModule.Types) {
73                                 if (!Annotations.IsMarked (type))
74                                         continue;
75
76                                 InitializeType (type);
77                         }
78                 }
79
80                 void InitializeType (TypeDefinition type)
81                 {
82                         MarkType (type);
83
84                         if (type.HasFields)
85                                 InitializeFields (type);
86                         if (type.HasMethods)
87                                 InitializeMethods (type.Methods);
88
89                         if (type.HasNestedTypes) {
90                                 foreach (var nested in type.NestedTypes) {
91                                         if (Annotations.IsMarked (nested))
92                                                 InitializeType (nested);
93                                 }
94                         }
95                 }
96
97                 void InitializeFields (TypeDefinition type)
98                 {
99                         foreach (FieldDefinition field in type.Fields)
100                                 if (Annotations.IsMarked (field))
101                                         MarkField (field);
102                 }
103
104                 void InitializeMethods (ICollection methods)
105                 {
106                         foreach (MethodDefinition method in methods)
107                                 if (Annotations.IsMarked (method))
108                                         EnqueueMethod (method);
109                 }
110
111                 void Process ()
112                 {
113                         if (QueueIsEmpty ())
114                                 throw new InvalidOperationException ("No entry methods");
115
116                         while (!QueueIsEmpty ()) {
117                                 ProcessQueue ();
118                                 ProcessVirtualMethods ();
119                         }
120                 }
121
122                 void ProcessQueue ()
123                 {
124                         while (!QueueIsEmpty ()) {
125                                 MethodDefinition method = (MethodDefinition) _methods.Dequeue ();
126                                 Annotations.Push (method);
127                                 ProcessMethod (method);
128                                 Annotations.Pop ();
129                         }
130                 }
131
132                 bool QueueIsEmpty ()
133                 {
134                         return _methods.Count == 0;
135                 }
136
137                 protected virtual void EnqueueMethod (MethodDefinition method)
138                 {
139                         _methods.Enqueue (method);
140                 }
141
142                 void ProcessVirtualMethods ()
143                 {
144                         foreach (MethodDefinition method in _virtual_methods) {
145                                 Annotations.Push (method);
146                                 ProcessVirtualMethod (method);
147                                 Annotations.Pop ();
148                         }
149                 }
150
151                 void ProcessVirtualMethod (MethodDefinition method)
152                 {
153                         IList overrides = Annotations.GetOverrides (method);
154                         if (overrides == null)
155                                 return;
156
157                         foreach (MethodDefinition @override in overrides)
158                                 ProcessOverride (@override);
159                 }
160
161                 void ProcessOverride (MethodDefinition method)
162                 {
163                         if (!Annotations.IsMarked (method.DeclaringType))
164                                 return;
165
166                         if (Annotations.IsProcessed (method))
167                                 return;
168
169                         if (Annotations.IsMarked (method))
170                                 return;
171
172                         MarkMethod (method);
173                         ProcessVirtualMethod (method);
174                 }
175
176                 void MarkMarshalSpec (IMarshalInfoProvider spec)
177                 {
178                         if (!spec.HasMarshalInfo)
179                                 return;
180
181                         var marshaler = spec.MarshalInfo as CustomMarshalInfo;
182                         if (marshaler == null)
183                                 return;
184
185                         MarkType (marshaler.ManagedType);
186                 }
187
188                 void MarkCustomAttributes (ICustomAttributeProvider provider)
189                 {
190                         if (!provider.HasCustomAttributes)
191                                 return;
192
193                         foreach (CustomAttribute ca in provider.CustomAttributes)
194                                 MarkCustomAttribute (ca);
195                 }
196
197                 protected virtual void MarkCustomAttribute (CustomAttribute ca)
198                 {
199                         Annotations.Push (ca);
200                         MarkMethod (ca.Constructor);
201
202                         MarkCustomAttributeArguments (ca);
203
204                         TypeReference constructor_type = ca.Constructor.DeclaringType;
205                         TypeDefinition type = constructor_type.Resolve ();
206                         if (type == null) {
207                                 Annotations.Pop ();
208                                 throw new ResolutionException (constructor_type);
209                         }
210
211                         MarkCustomAttributeProperties (ca, type);
212                         MarkCustomAttributeFields (ca, type);
213                         Annotations.Pop ();
214                 }
215
216                 protected void MarkSecurityDeclarations (ISecurityDeclarationProvider provider)
217                 {
218                         // most security declarations are removed (if linked) but user code might still have some
219                         // and if the attribtues references types then they need to be marked too
220                         if ((provider == null) || !provider.HasSecurityDeclarations)
221                                 return;
222
223                         foreach (var sd in provider.SecurityDeclarations)
224                                 MarkSecurityDeclaration (sd);
225                 }
226
227                 protected virtual void MarkSecurityDeclaration (SecurityDeclaration sd)
228                 {
229                         if (!sd.HasSecurityAttributes)
230                                 return;
231                         
232                         foreach (var sa in sd.SecurityAttributes)
233                                 MarkSecurityAttribute (sa);
234                 }
235
236                 protected virtual void MarkSecurityAttribute (SecurityAttribute sa)
237                 {
238                         TypeReference security_type = sa.AttributeType;
239                         TypeDefinition type = security_type.Resolve ();
240                         if (type == null)
241                                 throw new ResolutionException (security_type);
242                         
243                         MarkType (security_type);
244                         MarkSecurityAttributeProperties (sa, type);
245                         MarkSecurityAttributeFields (sa, type);
246                 }
247
248                 protected void MarkSecurityAttributeProperties (SecurityAttribute sa, TypeDefinition attribute)
249                 {
250                         if (!sa.HasProperties)
251                                 return;
252
253                         foreach (var named_argument in sa.Properties)
254                                 MarkCustomAttributeProperty (named_argument, attribute);
255                 }
256
257                 protected void MarkSecurityAttributeFields (SecurityAttribute sa, TypeDefinition attribute)
258                 {
259                         if (!sa.HasFields)
260                                 return;
261
262                         foreach (var named_argument in sa.Fields)
263                                 MarkCustomAttributeField (named_argument, attribute);
264                 }
265
266                 protected void MarkCustomAttributeProperties (CustomAttribute ca, TypeDefinition attribute)
267                 {
268                         if (!ca.HasProperties)
269                                 return;
270
271                         foreach (var named_argument in ca.Properties)
272                                 MarkCustomAttributeProperty (named_argument, attribute);
273                 }
274
275                 protected void MarkCustomAttributeProperty (CustomAttributeNamedArgument namedArgument, TypeDefinition attribute)
276                 {
277                         PropertyDefinition property = GetProperty (attribute, namedArgument.Name);
278                         Annotations.Push (property);
279                         if (property != null)
280                                 MarkMethod (property.SetMethod);
281
282                         MarkIfType (namedArgument.Argument);
283                         Annotations.Pop ();
284                 }
285
286                 PropertyDefinition GetProperty (TypeDefinition type, string propertyname)
287                 {
288                         while (type != null) {
289                                 PropertyDefinition property = type.Properties.FirstOrDefault (p => p.Name == propertyname);
290                                 if (property != null)
291                                         return property;
292
293                                 type = type.BaseType != null ? ResolveTypeDefinition (type.BaseType) : null;
294                         }
295
296                         return null;
297                 }
298
299                 protected void MarkCustomAttributeFields (CustomAttribute ca, TypeDefinition attribute)
300                 {
301                         if (!ca.HasFields)
302                                 return;
303
304                         foreach (var named_argument in ca.Fields)
305                                 MarkCustomAttributeField (named_argument, attribute);
306                 }
307
308                 protected void MarkCustomAttributeField (CustomAttributeNamedArgument namedArgument, TypeDefinition attribute)
309                 {
310                         FieldDefinition field = GetField (attribute, namedArgument.Name);
311                         if (field != null)
312                                 MarkField (field);
313
314                         MarkIfType (namedArgument.Argument);
315                 }
316
317                 FieldDefinition GetField (TypeDefinition type, string fieldname)
318                 {
319                         while (type != null) {
320                                 FieldDefinition field = type.Fields.FirstOrDefault (f => f.Name == fieldname);
321                                 if (field != null)
322                                         return field;
323
324                                 type = type.BaseType != null ? ResolveTypeDefinition (type.BaseType) : null;
325                         }
326
327                         return null;
328                 }
329
330                 void MarkCustomAttributeArguments (CustomAttribute ca)
331                 {
332                         if (!ca.HasConstructorArguments)
333                                 return;
334
335                         foreach (var argument in ca.ConstructorArguments)
336                                 MarkIfType (argument);
337                 }
338
339                 void MarkIfType (CustomAttributeArgument argument)
340                 {
341                         var at = argument.Type;
342                         if (at.IsArray) {
343                                 var et = at.GetElementType ();
344                                 if (et.Namespace != "System" || et.Name != "Type")
345                                         return;
346
347                                 MarkType (et);
348                                 if (argument.Value == null)
349                                         return;
350
351                                 foreach (var cac in (CustomAttributeArgument[]) argument.Value)
352                                         MarkWithResolvedScope ((TypeReference) cac.Value);
353                         } else if (at.Namespace == "System" && at.Name == "Type") {
354                                 MarkType (argument.Type);
355                                 MarkWithResolvedScope ((TypeReference) argument.Value);
356                         }
357                 }
358
359                 // custom attributes encoding means it's possible to have a scope that will point into a PCL facade
360                 // even if we (just before saving) will resolve all type references (bug #26752)
361                 void MarkWithResolvedScope (TypeReference type)
362                 {
363                         if (type == null)
364                                 return;
365
366                         // a GenericInstanceType can could contains generic arguments with scope that
367                         // needs to be updated out of the PCL facade (bug #28823)
368                         var git = (type as GenericInstanceType);
369                         if ((git != null) && git.HasGenericArguments) {
370                                 foreach (var ga in git.GenericArguments)
371                                         MarkWithResolvedScope (ga);
372                         }
373                         // we cannot set the Scope of a TypeSpecification but it's element type can be set
374                         // e.g. System.String[] -> System.String
375                         var ts = (type as TypeSpecification);
376                         if (ts != null) {
377                                 MarkWithResolvedScope (ts.GetElementType ());
378                                 return;
379                         }
380
381                         var td = type.Resolve ();
382                         if (td != null)
383                                 type.Scope = td.Scope;
384                         MarkType (type);
385                 }
386
387                 protected bool CheckProcessed (IMetadataTokenProvider provider)
388                 {
389                         if (Annotations.IsProcessed (provider))
390                                 return true;
391
392                         Annotations.Processed (provider);
393                         return false;
394                 }
395
396                 protected void MarkAssembly (AssemblyDefinition assembly)
397                 {
398                         if (CheckProcessed (assembly))
399                                 return;
400
401                         ProcessModule (assembly);
402
403                         MarkCustomAttributes (assembly);
404                         MarkSecurityDeclarations (assembly);
405
406                         foreach (ModuleDefinition module in assembly.Modules)
407                                 MarkCustomAttributes (module);
408                 }
409
410                 void ProcessModule (AssemblyDefinition assembly)
411                 {
412                         // Pre-mark <Module> if there is any methods as they need to be executed 
413                         // at assembly load time
414                         foreach (TypeDefinition type in assembly.MainModule.Types)
415                         {
416                                 if (type.Name == "<Module>" && type.HasMethods)
417                                 {
418                                         MarkType (type);
419                                         break;
420                                 }
421                         }
422                 }
423
424                 protected void MarkField (FieldReference reference)
425                 {
426 //                      if (IgnoreScope (reference.DeclaringType.Scope))
427 //                              return;
428
429                         if (reference.DeclaringType is GenericInstanceType)
430                                 MarkType (reference.DeclaringType);
431
432                         FieldDefinition field = ResolveFieldDefinition (reference);
433
434                         if (field == null)
435                                 throw new ResolutionException (reference);
436
437                         if (CheckProcessed (field))
438                                 return;
439
440                         MarkType (field.DeclaringType);
441                         MarkType (field.FieldType);
442                         MarkCustomAttributes (field);
443                         MarkMarshalSpec (field);
444
445                         Annotations.Mark (field);
446                 }
447
448                 protected virtual bool IgnoreScope (IMetadataScope scope)
449                 {
450                         AssemblyDefinition assembly = ResolveAssembly (scope);
451                         return Annotations.GetAction (assembly) != AssemblyAction.Link;
452                 }
453
454                 FieldDefinition ResolveFieldDefinition (FieldReference field)
455                 {
456                         FieldDefinition fd = field as FieldDefinition;
457                         if (fd == null)
458                                 fd = field.Resolve ();
459
460                         return fd;
461                 }
462
463                 void MarkScope (IMetadataScope scope)
464                 {
465                         var provider = scope as IMetadataTokenProvider;
466                         if (provider == null)
467                                 return;
468
469                         Annotations.Mark (provider);
470                 }
471
472                 protected virtual void MarkSerializable (TypeDefinition type)
473                 {
474                         MarkDefaultConstructor (type);
475                         MarkMethodsIf (type.Methods, IsSpecialSerializationConstructorPredicate);
476                 }
477
478                 protected virtual TypeDefinition MarkType (TypeReference reference)
479                 {
480                         if (reference == null)
481                                 return null;
482
483                         reference = GetOriginalType (reference);
484
485                         if (reference is GenericParameter)
486                                 return null;
487
488 //                      if (IgnoreScope (reference.Scope))
489 //                              return;
490
491                         TypeDefinition type = ResolveTypeDefinition (reference);
492
493                         if (type == null)
494                                 throw new ResolutionException (reference);
495
496                         if (CheckProcessed (type))
497                                 return null;
498
499                         Annotations.Push (type);
500
501                         MarkScope (type.Scope);
502                         MarkType (type.BaseType);
503                         MarkType (type.DeclaringType);
504                         MarkCustomAttributes (type);
505                         MarkSecurityDeclarations (type);
506
507                         if (IsMulticastDelegate (type)) {
508                                 MarkMethodCollection (type.Methods);
509                         }
510
511                         if (IsSerializable (type))
512                                 MarkSerializable (type);
513
514                         MarkTypeSpecialCustomAttributes (type);
515
516                         MarkGenericParameterProvider (type);
517
518                         // keep fields for value-types and for classes with LayoutKind.Sequential or Explicit
519                         if (type.IsValueType || !type.IsAutoLayout)
520                                 MarkFields (type, type.IsEnum);
521
522                         if (type.HasInterfaces) {
523                                 foreach (TypeReference iface in type.Interfaces)
524                                         MarkType (iface);
525                         }
526
527                         if (type.HasMethods) {
528                                 MarkMethodsIf (type.Methods, IsVirtualAndHasPreservedParent);
529                                 MarkMethodsIf (type.Methods, IsStaticConstructorPredicate);
530                         }
531
532                         DoAdditionalTypeProcessing (type);
533
534                         Annotations.Pop ();
535
536                         Annotations.Mark (type);
537
538                         ApplyPreserveInfo (type);
539
540                         return type;
541                 }
542
543                 // Allow subclassers to mark additional things when marking a method
544                 protected virtual void DoAdditionalTypeProcessing (TypeDefinition method)
545                 {
546                 }
547
548                 void MarkTypeSpecialCustomAttributes (TypeDefinition type)
549                 {
550                         if (!type.HasCustomAttributes)
551                                 return;
552
553                         foreach (CustomAttribute attribute in type.CustomAttributes) {
554                                 switch (attribute.Constructor.DeclaringType.FullName) {
555                                 case "System.Xml.Serialization.XmlSchemaProviderAttribute":
556                                         MarkXmlSchemaProvider (type, attribute);
557                                         break;
558                                 }
559                         }
560                 }
561
562                 void MarkMethodSpecialCustomAttributes (MethodDefinition method)
563                 {
564                         if (!method.HasCustomAttributes)
565                                 return;
566
567                         foreach (CustomAttribute attribute in method.CustomAttributes) {
568                                 switch (attribute.Constructor.DeclaringType.FullName) {
569                                 case "System.Web.Services.Protocols.SoapHeaderAttribute":
570                                         MarkSoapHeader (method, attribute);
571                                         break;
572                                 }
573                         }
574                 }
575
576                 void MarkXmlSchemaProvider (TypeDefinition type, CustomAttribute attribute)
577                 {
578                         string method_name;
579                         if (!TryGetStringArgument (attribute, out method_name))
580                                 return;
581
582                         MarkNamedMethod (type, method_name);
583                 }
584
585                 static bool TryGetStringArgument (CustomAttribute attribute, out string argument)
586                 {
587                         argument = null;
588
589                         if (attribute.ConstructorArguments.Count < 1)
590                                 return false;
591
592                         argument = attribute.ConstructorArguments [0].Value as string;
593
594                         return argument != null;
595                 }
596
597                 protected int MarkNamedMethod (TypeDefinition type, string method_name)
598                 {
599                         if (!type.HasMethods)
600                                 return 0;
601
602                         int count = 0;
603                         foreach (MethodDefinition method in type.Methods) {
604                                 if (method.Name != method_name)
605                                         continue;
606
607                                 MarkMethod (method);
608                                 count++;
609                         }
610
611                         return count;
612                 }
613
614                 void MarkSoapHeader (MethodDefinition method, CustomAttribute attribute)
615                 {
616                         string member_name;
617                         if (!TryGetStringArgument (attribute, out member_name))
618                                 return;
619
620                         MarkNamedField (method.DeclaringType, member_name);
621                         MarkNamedProperty (method.DeclaringType, member_name);
622                 }
623
624                 void MarkNamedField (TypeDefinition type, string field_name)
625                 {
626                         if (!type.HasFields)
627                                 return;
628
629                         foreach (FieldDefinition field in type.Fields) {
630                                 if (field.Name != field_name)
631                                         continue;
632
633                                 MarkField (field);
634                         }
635                 }
636
637                 void MarkNamedProperty (TypeDefinition type, string property_name)
638                 {
639                         if (!type.HasProperties)
640                                 return;
641
642                         foreach (PropertyDefinition property in type.Properties) {
643                                 if (property.Name != property_name)
644                                         continue;
645
646                                 Annotations.Push (property);
647                                 MarkMethod (property.GetMethod);
648                                 MarkMethod (property.SetMethod);
649                                 Annotations.Pop ();
650                         }
651                 }
652
653                 void MarkGenericParameterProvider (IGenericParameterProvider provider)
654                 {
655                         if (!provider.HasGenericParameters)
656                                 return;
657
658                         foreach (GenericParameter parameter in provider.GenericParameters)
659                                 MarkGenericParameter (parameter);
660                 }
661
662                 void MarkGenericParameter (GenericParameter parameter)
663                 {
664                         MarkCustomAttributes (parameter);
665                         foreach (TypeReference constraint in parameter.Constraints)
666                                 MarkType (constraint);
667                 }
668
669                 bool IsVirtualAndHasPreservedParent (MethodDefinition method)
670                 {
671                         if (!method.IsVirtual)
672                                 return false;
673
674                         var base_list = Annotations.GetBaseMethods (method);
675                         if (base_list == null)
676                                 return false;
677
678                         foreach (MethodDefinition @base in base_list) {
679                                 if (IgnoreScope (@base.DeclaringType.Scope))
680                                         return true;
681
682                                 if (IsVirtualAndHasPreservedParent (@base))
683                                         return true;
684                         }
685
686                         return false;
687                 }
688
689                 static MethodPredicate IsSpecialSerializationConstructorPredicate = new MethodPredicate (IsSpecialSerializationConstructor);
690
691                 static bool IsSpecialSerializationConstructor (MethodDefinition method)
692                 {
693                         if (!IsConstructor (method))
694                                 return false;
695
696                         var parameters = method.Parameters;
697                         if (parameters.Count != 2)
698                                 return false;
699
700                         return parameters [0].ParameterType.Name == "SerializationInfo" &&
701                                 parameters [1].ParameterType.Name == "StreamingContext";
702                 }
703
704                 delegate bool MethodPredicate (MethodDefinition method);
705
706                 void MarkMethodsIf (ICollection methods, MethodPredicate predicate)
707                 {
708                         foreach (MethodDefinition method in methods)
709                                 if (predicate (method)) {
710                                         Annotations.Push (predicate);
711                                         MarkMethod (method);
712                                         Annotations.Pop ();
713                                 }
714                 }
715
716                 static MethodPredicate IsDefaultConstructorPredicate = new MethodPredicate (IsDefaultConstructor);
717
718                 static bool IsDefaultConstructor (MethodDefinition method)
719                 {
720                         return IsConstructor (method) && !method.HasParameters;
721                 }
722
723                 static bool IsConstructor (MethodDefinition method)
724                 {
725                         return method.IsConstructor && !method.IsStatic;
726                 }
727
728                 protected void MarkDefaultConstructor (TypeDefinition type)
729                 {
730                         if ((type == null) || !type.HasMethods)
731                                 return;
732
733                         MarkMethodsIf (type.Methods, IsDefaultConstructorPredicate);
734                 }
735
736                 static MethodPredicate IsStaticConstructorPredicate = new MethodPredicate (IsStaticConstructor);
737
738                 static bool IsStaticConstructor (MethodDefinition method)
739                 {
740                         return method.IsConstructor && method.IsStatic;
741                 }
742
743                 static bool IsSerializable (TypeDefinition td)
744                 {
745                         return (td.Attributes & TypeAttributes.Serializable) != 0;
746                 }
747
748                 static bool IsMulticastDelegate (TypeDefinition td)
749                 {
750                         return td.BaseType != null && td.BaseType.FullName == "System.MulticastDelegate";
751                 }
752
753                 protected TypeDefinition ResolveTypeDefinition (TypeReference type)
754                 {
755                         TypeDefinition td = type as TypeDefinition;
756                         if (td == null)
757                                 td = type.Resolve ();
758
759                         return td;
760                 }
761
762                 protected TypeReference GetOriginalType (TypeReference type)
763                 {
764                         while (type is TypeSpecification) {
765                                 GenericInstanceType git = type as GenericInstanceType;
766                                 if (git != null)
767                                         MarkGenericArguments (git);
768
769                                 var mod = type as IModifierType;
770                                 if (mod != null)
771                                         MarkModifierType (mod);
772
773                                 type = ((TypeSpecification) type).ElementType;
774                         }
775
776                         return type;
777                 }
778
779                 void MarkModifierType (IModifierType mod)
780                 {
781                         MarkType (mod.ModifierType);
782                 }
783
784                 void MarkGenericArguments (IGenericInstance instance)
785                 {
786                         foreach (TypeReference argument in instance.GenericArguments)
787                                 MarkType (argument);
788
789                         MarkGenericArgumentConstructors (instance);
790                 }
791
792                 void MarkGenericArgumentConstructors (IGenericInstance instance)
793                 {
794                         var arguments = instance.GenericArguments;
795
796                         var generic_element = GetGenericProviderFromInstance (instance);
797                         if (generic_element == null)
798                                 return;
799
800                         var parameters = generic_element.GenericParameters;
801
802                         if (arguments.Count != parameters.Count)
803                                 return;
804
805                         for (int i = 0; i < arguments.Count; i++) {
806                                 var argument = arguments [i];
807                                 var parameter = parameters [i];
808
809                                 if (!parameter.HasDefaultConstructorConstraint)
810                                         continue;
811
812                                 var argument_definition = ResolveTypeDefinition (argument);
813                                 if (argument_definition == null)
814                                         continue;
815
816                                 MarkMethodsIf (argument_definition.Methods, ctor => !ctor.IsStatic && !ctor.HasParameters);
817                         }
818                 }
819
820                 IGenericParameterProvider GetGenericProviderFromInstance (IGenericInstance instance)
821                 {
822                         var method = instance as GenericInstanceMethod;
823                         if (method != null)
824                                 return ResolveMethodDefinition (method.ElementMethod);
825
826                         var type = instance as GenericInstanceType;
827                         if (type != null)
828                                 return ResolveTypeDefinition (type.ElementType);
829
830                         return null;
831                 }
832
833                 void ApplyPreserveInfo (TypeDefinition type)
834                 {
835                         ApplyPreserveMethods (type);
836
837                         if (!Annotations.IsPreserved (type))
838                                 return;
839
840                         switch (Annotations.GetPreserve (type)) {
841                         case TypePreserve.All:
842                                 MarkFields (type, true);
843                                 MarkMethods (type);
844                                 break;
845                         case TypePreserve.Fields:
846                                 MarkFields (type, true);
847                                 break;
848                         case TypePreserve.Methods:
849                                 MarkMethods (type);
850                                 break;
851                         }
852                 }
853
854                 void ApplyPreserveMethods (TypeDefinition type)
855                 {
856                         var list = Annotations.GetPreservedMethods (type);
857                         if (list == null)
858                                 return;
859
860                         MarkMethodCollection (list);
861                 }
862
863                 void ApplyPreserveMethods (MethodDefinition method)
864                 {
865                         var list = Annotations.GetPreservedMethods (method);
866                         if (list == null)
867                                 return;
868
869                         MarkMethodCollection (list);
870                 }
871
872                 protected void MarkFields (TypeDefinition type, bool includeStatic)
873                 {
874                         if (!type.HasFields)
875                                 return;
876
877                         foreach (FieldDefinition field in type.Fields) {
878                                 if (!includeStatic && field.IsStatic)
879                                         continue;
880                                 MarkField (field);
881                         }
882                 }
883
884                 protected virtual void MarkMethods (TypeDefinition type)
885                 {
886                         if (type.HasMethods)
887                                 MarkMethodCollection (type.Methods);
888                 }
889
890                 void MarkMethodCollection (IEnumerable methods)
891                 {
892                         foreach (MethodDefinition method in methods)
893                                 MarkMethod (method);
894                 }
895
896                 protected virtual MethodDefinition MarkMethod (MethodReference reference)
897                 {
898                         reference = GetOriginalMethod (reference);
899
900                         if (reference.DeclaringType is ArrayType)
901                                 return null;
902
903                         Annotations.Push (reference);
904                         if (reference.DeclaringType is GenericInstanceType)
905                                 MarkType (reference.DeclaringType);
906
907 //                      if (IgnoreScope (reference.DeclaringType.Scope))
908 //                              return;
909
910                         MethodDefinition method = ResolveMethodDefinition (reference);
911
912                         if (method == null) {
913                                 Annotations.Pop ();
914                                 throw new ResolutionException (reference);
915                         }
916
917                         if (Annotations.GetAction (method) == MethodAction.Nothing)
918                                 Annotations.SetAction (method, MethodAction.Parse);
919
920                         EnqueueMethod (method);
921
922                         Annotations.Pop ();
923                         Annotations.AddDependency (method);
924
925                         return method;
926                 }
927
928                 AssemblyDefinition ResolveAssembly (IMetadataScope scope)
929                 {
930                         AssemblyDefinition assembly = _context.Resolve (scope);
931                         MarkAssembly (assembly);
932                         return assembly;
933                 }
934
935                 protected MethodReference GetOriginalMethod (MethodReference method)
936                 {
937                         while (method is MethodSpecification) {
938                                 GenericInstanceMethod gim = method as GenericInstanceMethod;
939                                 if (gim != null)
940                                         MarkGenericArguments (gim);
941
942                                 method = ((MethodSpecification) method).ElementMethod;
943                         }
944
945                         return method;
946                 }
947
948                 MethodDefinition ResolveMethodDefinition (MethodReference method)
949                 {
950                         MethodDefinition md = method as MethodDefinition;
951                         if (md == null)
952                                 md = method.Resolve ();
953
954                         return md;
955                 }
956
957                 protected virtual void ProcessMethod (MethodDefinition method)
958                 {
959                         if (CheckProcessed (method))
960                                 return;
961
962                         Annotations.Push (method);
963                         MarkType (method.DeclaringType);
964                         MarkCustomAttributes (method);
965                         MarkSecurityDeclarations (method);
966
967                         MarkGenericParameterProvider (method);
968
969                         if (IsPropertyMethod (method))
970                                 MarkProperty (GetProperty (method));
971                         else if (IsEventMethod (method))
972                                 MarkEvent (GetEvent (method));
973
974                         if (method.HasParameters) {
975                                 foreach (ParameterDefinition pd in method.Parameters) {
976                                         MarkType (pd.ParameterType);
977                                         MarkCustomAttributes (pd);
978                                         MarkMarshalSpec (pd);
979                                 }
980                         }
981
982                         if (method.HasOverrides) {
983                                 foreach (MethodReference ov in method.Overrides)
984                                         MarkMethod (ov);
985                         }
986
987                         MarkMethodSpecialCustomAttributes (method);
988
989                         if (method.IsVirtual)
990                                 _virtual_methods.Add (method);
991
992                         MarkBaseMethods (method);
993
994                         MarkType (method.ReturnType);
995                         MarkCustomAttributes (method.MethodReturnType);
996                         MarkMarshalSpec (method.MethodReturnType);
997
998                         if (ShouldParseMethodBody (method))
999                                 MarkMethodBody (method.Body);
1000
1001                         DoAdditionalMethodProcessing (method);
1002
1003                         Annotations.Mark (method);
1004
1005                         ApplyPreserveMethods (method);
1006                         Annotations.Pop ();
1007                 }
1008
1009                 // Allow subclassers to mark additional things when marking a method
1010                 protected virtual void DoAdditionalMethodProcessing (MethodDefinition method)
1011                 {
1012                 }
1013
1014                 void MarkBaseMethods (MethodDefinition method)
1015                 {
1016                         IList base_methods = Annotations.GetBaseMethods (method);
1017                         if (base_methods == null)
1018                                 return;
1019
1020                         foreach (MethodDefinition base_method in base_methods) {
1021                                 if (base_method.DeclaringType.IsInterface && !method.DeclaringType.IsInterface)
1022                                         continue;
1023
1024                                 MarkMethod (base_method);
1025                                 MarkBaseMethods (base_method);
1026                         }
1027                 }
1028
1029                 bool ShouldParseMethodBody (MethodDefinition method)
1030                 {
1031                         if (!method.HasBody)
1032                                 return false;
1033
1034                         AssemblyDefinition assembly = ResolveAssembly (method.DeclaringType.Scope);
1035                         return (Annotations.GetAction (method) == MethodAction.ForceParse ||
1036                                 (Annotations.GetAction (assembly) == AssemblyAction.Link && Annotations.GetAction (method) == MethodAction.Parse));
1037                 }
1038
1039                 static internal bool IsPropertyMethod (MethodDefinition md)
1040                 {
1041                         return (md.SemanticsAttributes & MethodSemanticsAttributes.Getter) != 0 ||
1042                                 (md.SemanticsAttributes & MethodSemanticsAttributes.Setter) != 0;
1043                 }
1044
1045                 static bool IsEventMethod (MethodDefinition md)
1046                 {
1047                         return (md.SemanticsAttributes & MethodSemanticsAttributes.AddOn) != 0 ||
1048                                 (md.SemanticsAttributes & MethodSemanticsAttributes.Fire) != 0 ||
1049                                 (md.SemanticsAttributes & MethodSemanticsAttributes.RemoveOn) != 0;
1050                 }
1051
1052                 static internal PropertyDefinition GetProperty (MethodDefinition md)
1053                 {
1054                         TypeDefinition declaringType = (TypeDefinition) md.DeclaringType;
1055                         foreach (PropertyDefinition prop in declaringType.Properties)
1056                                 if (prop.GetMethod == md || prop.SetMethod == md)
1057                                         return prop;
1058
1059                         return null;
1060                 }
1061
1062                 static EventDefinition GetEvent (MethodDefinition md)
1063                 {
1064                         TypeDefinition declaringType = (TypeDefinition) md.DeclaringType;
1065                         foreach (EventDefinition evt in declaringType.Events)
1066                                 if (evt.AddMethod == md || evt.InvokeMethod == md || evt.RemoveMethod == md)
1067                                         return evt;
1068
1069                         return null;
1070                 }
1071
1072                 protected void MarkProperty (PropertyDefinition prop)
1073                 {
1074                         MarkCustomAttributes (prop);
1075                 }
1076
1077                 protected void MarkEvent (EventDefinition evt)
1078                 {
1079                         MarkCustomAttributes (evt);
1080                         MarkMethodIfNotNull (evt.AddMethod);
1081                         MarkMethodIfNotNull (evt.InvokeMethod);
1082                         MarkMethodIfNotNull (evt.RemoveMethod);
1083                 }
1084
1085                 void MarkMethodIfNotNull (MethodReference method)
1086                 {
1087                         if (method == null)
1088                                 return;
1089
1090                         MarkMethod (method);
1091                 }
1092
1093                 protected virtual void MarkMethodBody (MethodBody body)
1094                 {
1095                         foreach (VariableDefinition var in body.Variables)
1096                                 MarkType (var.VariableType);
1097
1098                         foreach (ExceptionHandler eh in body.ExceptionHandlers)
1099                                 if (eh.HandlerType == ExceptionHandlerType.Catch)
1100                                         MarkType (eh.CatchType);
1101
1102                         foreach (Instruction instruction in body.Instructions)
1103                                 MarkInstruction (instruction);
1104                 }
1105
1106                 protected virtual void MarkInstruction (Instruction instruction)
1107                 {
1108                         switch (instruction.OpCode.OperandType) {
1109                         case OperandType.InlineField:
1110                                 MarkField ((FieldReference) instruction.Operand);
1111                                 break;
1112                         case OperandType.InlineMethod:
1113                                 MarkMethod ((MethodReference) instruction.Operand);
1114                                 break;
1115                         case OperandType.InlineTok:
1116                                 object token = instruction.Operand;
1117                                 if (token is TypeReference)
1118                                         MarkType ((TypeReference) token);
1119                                 else if (token is MethodReference)
1120                                         MarkMethod ((MethodReference) token);
1121                                 else
1122                                         MarkField ((FieldReference) token);
1123                                 break;
1124                         case OperandType.InlineType:
1125                                 MarkType ((TypeReference) instruction.Operand);
1126                                 break;
1127                         default:
1128                                 break;
1129                         }
1130                 }
1131         }
1132 }