/
CCodeGenerator.class.st
5688 lines (5064 loc) · 210 KB
/
CCodeGenerator.class.st
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
"
This class oversees the translation of a subset of Smalltalk to C, allowing the comforts of Smalltalk during development and the efficiency and portability of C for the resulting interpreter.
See VMMaker for more useful info
"
Class {
#name : #CCodeGenerator,
#superclass : #Object,
#instVars : [
'vmClass',
'structClasses',
'translationDict',
'asArgumentTranslationDict',
'inlineList',
'constants',
'variables',
'variableDeclarations',
'scopeStack',
'methods',
'macros',
'apiMethods',
'apiVariables',
'kernelReturnTypes',
'currentMethod',
'headerFiles',
'globalVariableUsage',
'useSymbolicConstants',
'generateDeadCode',
'requiredSelectors',
'previousCommentMarksInlining',
'previousCommenter',
'logger',
'suppressAsmLabels',
'asmLabelCounts',
'pools',
'selectorTranslations',
'staticallyResolvedPolymorphicReceivers',
'optionsDictionary',
'breakSrcInlineSelectors',
'breakDestInlineSelectors',
'breakOnInline',
'vmMaker'
],
#classVars : [
'NoRegParmsInAssertVMs'
],
#pools : [
'VMBasicConstants'
],
#category : #'VMMaker-Translation to C'
}
{ #category : #'class initialization' }
CCodeGenerator class >> initialize [
"CCodeGenerator initialize"
NoRegParmsInAssertVMs := true
"If NoRegParmsInAssertVMs is true the generator spits out an attribute turning off register parameters for static functions in the Assert and Debug VMs which makes debugging easier, since all functions can be safely called from gdb. One might hope that -mregparm=0 would work but at least on Mac OS X's gcc 4.2.1 it does not and hence we have to use a per funciton attribute. Sigh..."
]
{ #category : #testing }
CCodeGenerator class >> isVarargsSelector: aSymbol [
^aSymbol endsWith: 'printf:'
]
{ #category : #'C code generator' }
CCodeGenerator class >> monticelloDescriptionFor: aClass [
"Answer a suitable Monticello package stamp to include in the header."
| pkgInfo pkg uuid |
pkgInfo := PackageOrganizer default packageOfClass: aClass.
pkg := MCWorkingCopy allManagers detect: [:ea| ea packageName = pkgInfo packageName].
pkg ancestry ancestors isEmpty ifFalse:
[uuid := pkg ancestry ancestors first id].
^aClass name, (pkg modified ifTrue: [' * '] ifFalse: [' ']), pkg ancestry ancestorString, ' uuid: ', uuid asString
]
{ #category : #'removing from system' }
CCodeGenerator class >> removeCompilerMethods [
"Before removing the C code generator classes from the system, use this method to remove the compiler node methods that support it. This avoids leaving dangling references to C code generator classes in the compiler node classes."
ParseNode withAllSubclasses do: [ :nodeClass |
nodeClass removeCategory: 'C translation'.
].
Smalltalk at: #AbstractSound ifPresent: [:abstractSound |
abstractSound class removeCategory: 'primitive generation'].
]
{ #category : #'C code generator' }
CCodeGenerator class >> shortMonticelloDescriptionForClass: aClass [
"Answer a suitable Monticello package stamp to include in a moduleName."
| mdesc |
mdesc := [self monticelloDescriptionFor: aClass]
on: Error
do: [:ex| ^' ', Date today asString].
^mdesc copyFrom: 1 to: (mdesc indexOfSubCollection: ' uuid:') - 1
]
{ #category : #accessing }
CCodeGenerator >> abortBlock [
^vmMaker ifNotNil: [:vmm| vmm abortBlock]
]
{ #category : #'spur primitive compilation' }
CCodeGenerator >> accessorChainsForMethod: method interpreterClass: interpreterClass [
"Answer a set of access paths from arguments through objects, in the method, assuming
it is a primitive. This is in support of Spur's lazy become. A primitive may fail because it
may encounter a forwarder. The primitive failure code needs to know to what depth it
must follow arguments to follow forwarders and, if any are found and followed, retry the
primitive. This method determines that depth. It starts by collecting references to the
stack and then follows these through assignments to variables and use of accessor
methods such as fetchPointer:ofObject:. For example
| obj field |
obj := self stackTop.
field := objectMemory fetchPointer: 1 ofObject: obj.
self storePointer: 1 ofObject: field withValue: (self stackValue: 1)
has depth 2, since field is accessed, and field is an element of obj."
| accessors assignments roots chains extendedChains extended lastPass |
self accessorsAndAssignmentsForMethod: method
actuals: (self actualsForMethod: method)
depth: 0
interpreterClass: interpreterClass
into: [:theRoots :theAccessors :theAssignments|
roots := theRoots.
accessors := theAccessors.
assignments := theAssignments].
"Compute the transitive closure of assignments of accessor sends or variables to variables from the roots.
Start from the stack accesses (the roots).
On the last pass look only for accessors of the targets of the tip assignments."
chains := OrderedCollection new.
roots do: [:root| chains addAll: (assignments
select: [:assignment| assignment expression = root]
thenCollect: [:assignment| OrderedCollection with: assignment])].
lastPass := false.
[extended := false.
extendedChains := OrderedCollection new: chains size * 2.
chains do:
[:chain| | tip refs accessorRefs variableRefs |
tip := chain last variable.
refs := accessors select: [:send| send args anySatisfy: [:arg| tip isSameAs: arg]].
lastPass ifFalse:
[accessorRefs := refs collect: [:send|
assignments
detect: [:assignment|
assignment expression = send
and: [(chain includes: assignment) not]]
ifNone: []]
thenSelect: [:assignmentOrNil| assignmentOrNil notNil].
variableRefs := assignments select:
[:assignment|
(tip isSameAs: assignment expression)
and: [(tip isSameAs: assignment variable) not
and: [(chain includes: assignment) not]]].
refs := (Set withAll: accessorRefs) addAll: variableRefs; yourself].
refs isEmpty
ifTrue:
[extendedChains add: chain]
ifFalse:
[lastPass ifFalse: [extended := true].
self assert: (refs noneSatisfy: [:assignment| chain includes: assignment]).
extendedChains addAll: (refs collect: [:assignment| chain, {assignment}])]].
extended or: [lastPass not]] whileTrue:
[chains := extendedChains.
extended ifFalse: [lastPass := true]].
^chains
]
{ #category : #'spur primitive compilation' }
CCodeGenerator >> accessorDepthDeterminationFollowsSelfSends [
^false
]
{ #category : #'spur primitive compilation' }
CCodeGenerator >> accessorDepthForChain: chain [ "OrderedCollection"
"Answer the actual number of accessors in the access chain, filtering out assignments of variables to variables."
| accessorDepth |
accessorDepth := 0.
chain do:
[:node|
((node isAssignment and: [node expression isVariable])
or: [node isSend and: [SpurMemoryManager isSameLevelObjectAccessor: node selector]]) ifFalse:
[accessorDepth := accessorDepth + 1]].
^accessorDepth
]
{ #category : #'spur primitive compilation' }
CCodeGenerator >> accessorDepthForMethod: method [
"Compute the depth the method traverses object structure, assuming it is a primitive.
This is in support of Spur's lazy become. A primitive may fail because it may encounter
a forwarder. The primitive failure code needs to know to what depth it must follow
arguments to follow forwarders and, if any are found and followed, retry the primitive.
This method determines that depth. It starts by collecting references to the stack and
then follows these through assignments to variables and use of accessor methods
such as fetchPointer:ofObject:. For example
| obj field |
obj := self stackTop.
field := objectMemory fetchPointer: 1 ofObject: obj.
self storePointer: 1 ofObject: field withValue: (self stackValue: 1)
has depth 2, since field is accessed, and field is an element of obj."
^((method definingClass includesSelector: method selector) ifTrue:
[(method definingClass >> method selector) pragmaAt: #accessorDepth:])
ifNil:
[((self
accessorChainsForMethod: method
interpreterClass: (vmClass ifNil: [StackInterpreter]))
inject: 0
into: [:length :chain| length max: (self accessorDepthForChain: chain)]) - 1]
ifNotNil: [:pragma| pragma arguments first]
]
{ #category : #'spur primitive compilation' }
CCodeGenerator >> accessorDepthForSelector: selector [
^(selector = #initialiseModule
or: [InterpreterPlugin includesSelector: selector]) ifFalse:
[(self methodNamed: selector) ifNotNil:
[:m| self accessorDepthForMethod: m]]
]
{ #category : #'spur primitive compilation' }
CCodeGenerator >> accessorsAndAssignmentsForMethod: method actuals: actualParameters depth: depth interpreterClass: interpreterClass into: aTrinaryBlock [
"Evaluate aTrinaryBlock with the root accessor sends, accessor sends and assignments in the method."
| accessors assignments roots |
accessors := Set new.
assignments := Set new.
roots := Set new.
actualParameters with: method args do:
[:actual :argName|
(actual isVariable or: [actual isSend]) ifTrue:
[(actual isSend and: [self isStackAccessor: actual selector given: interpreterClass]) ifTrue:
[roots add: actual].
assignments add: (TAssignmentNode new
setVariable: (TVariableNode new setName: argName)
expression: actual)]].
method parseTree nodesDo:
[:node|
node isSend ifTrue:
[(self isStackAccessor: node selector given: interpreterClass) ifTrue:
[roots add: node].
(self isObjectAccessor: node selector given: interpreterClass) ifTrue:
[accessors add: node].
(self accessorDepthDeterminationFollowsSelfSends
and: [node receiver isVariable
and: [node receiver name = 'self'
and: [roots isEmpty
or: [node args anySatisfy:
[:arg|
(roots includes: arg)
or: [(accessors includes: arg)
or: [assignments anySatisfy: [:assignment| assignment variable isSameAs: arg]]]]]]]]) ifTrue:
[self accessorsAndAssignmentsForSubMethodNamed: node selector
actuals: node args
depth: depth + 1
interpreterClass: interpreterClass
into: [:subRoots :subAccessors :subAssignments|
(subRoots isEmpty and: [subAccessors isEmpty and: [subAssignments isEmpty]]) ifFalse:
[roots addAll: subRoots.
accessors add: node.
accessors addAll: subAccessors.
assignments addAll: subAssignments]]]].
(node isAssignment
and: [(node expression isSend and: [SpurMemoryManager isTerminalObjectAccessor: node expression selector]) not
and: [(roots includes: node expression)
or: [(accessors includes: node expression)
or: [node expression isVariable and: [node expression name ~= 'nil']]]]]) ifTrue:
[assignments add: node]].
^aTrinaryBlock
value: roots
value: accessors
value: assignments
]
{ #category : #'spur primitive compilation' }
CCodeGenerator >> actualsForMethod: aTMethod [
"Normal primitives have no arguments, but translated primitives do.
This class doesn't handle translated primitives and so smply answers an empty array.
Subclasses override as required."
^#()
]
{ #category : #public }
CCodeGenerator >> addAllClassVarsFor: aClass [
"Add the class variables for the given class (and its superclasses) to the code base as constants."
| allClasses |
allClasses := aClass withAllSuperclasses.
allClasses do: [:c | self addClassVarsFor: c].
]
{ #category : #public }
CCodeGenerator >> addClass: aClass [
"Add the variables and methods of the given class to the code base."
aClass prepareToBeAddedToCodeGenerator: self.
self checkClassForNameConflicts: aClass.
self addClassVarsFor: aClass.
"ikp..."
self addPoolVarsFor: aClass.
(aClass inheritsFrom: VMStructType) ifFalse:
[variables addAll: (self instVarNamesForClass: aClass)].
self retainMethods: (aClass requiredMethodNames: self options).
UIManager default
displayProgress: 'Adding Class ' , aClass name , '...'
from: 0
to: aClass selectors size
during:
[:bar |
aClass selectors doWithIndex:
[:sel :i | | source |
bar value: i.
self addMethodFor: aClass selector: sel]].
aClass declareCVarsIn: self
]
{ #category : #public }
CCodeGenerator >> addClassVarsFor: aClass [
"Add the class variables for the given class to the code base as constants."
aClass classPool associationsDo:
[:assoc | self addConstantForBinding: assoc]
]
{ #category : #public }
CCodeGenerator >> addConstantForBinding: variableBinding [
"Add the pool variable to the code base as a constant."
| node val |
val := variableBinding value.
node := (useSymbolicConstants and: [self isCLiteral: val])
ifTrue:[TDefineNode new
setName: variableBinding key
value: variableBinding value]
ifFalse:[TConstantNode new setValue: variableBinding value].
constants at: variableBinding key put: node
]
{ #category : #public }
CCodeGenerator >> addHeaderFile: aString [
"Add a header file. As a hack we allow C preprocessor defs such as #ifdef"
self assert: (('"<#' includes: aString first) or: [(aString last: 2) = '_H']).
(aString first ~= $#
and: [headerFiles includes: aString]) ifTrue:
[logger nextPutAll: 'warning, attempt to include ', aString, ' a second time'; cr; flush.
^self].
headerFiles addLast: aString
]
{ #category : #public }
CCodeGenerator >> addHeaderFileFirst: aString [
"Add a header file to the front of the sequence."
self assert: (('"<' includes: aString first) and: ['">' includes: aString last]).
self assert: (headerFiles includes: aString) not.
headerFiles addFirst: aString
]
{ #category : #public }
CCodeGenerator >> addMacro: aString for: selector [
"Add a macro. aString must be the macro arguments and body without the leading #define or name"
macros at: selector put: aString
]
{ #category : #utilities }
CCodeGenerator >> addMethod: aTMethod [
"Add the given method to the code base and answer it.
Only allow duplicate definitions for struct accessors, since we don't actually
generate code for these methods and hence the conflict doesn't matter.
Allow subclasses to redefine methods (Smalltalk has inheritance after all)."
(methods at: aTMethod selector ifAbsent: []) ifNotNil:
[:conflict |
aTMethod compiledMethod isSubclassResponsibility ifTrue:
[^nil].
(conflict isStructAccessor
and: [aTMethod isStructAccessor
and: [conflict compiledMethod decompileString = aTMethod compiledMethod decompileString]]) ifTrue:
[^nil].
((aTMethod definingClass inheritsFrom: conflict definingClass)
or: [(aTMethod compiledMethod pragmaAt: #option:) notNil]) ifFalse:
[self error: 'Method name conflict: ', aTMethod selector]].
^methods at: aTMethod selector put: aTMethod
]
{ #category : #utilities }
CCodeGenerator >> addMethodFor: aClass selector: selector [
"Add the given method to the code base and answer its translation
or nil if it shouldn't be translated."
| method tmethod |
method := aClass compiledMethodAt: selector.
(method pragmaAt: #doNotGenerate) ifNotNil:
["only remove a previous method if this one overrides it, i.e. this is a subclass method.
If the existing method is in a different hierarchy this method must be merely a redeirect."
(methods at: selector ifAbsent: []) ifNotNil:
[:tm|
(aClass includesBehavior: tm definingClass) ifTrue:
[self removeMethodForSelector: selector]].
^nil].
method isSubclassResponsibility ifTrue:
[^nil].
(self shouldIncludeMethodFor: aClass selector: selector) ifFalse:
[^nil].
tmethod := self compileToTMethodSelector: selector in: aClass.
"Even though we exclude initialize methods, we must consider their
global variable usage, otherwise globals may be incorrectly localized."
selector == #initialize ifTrue:
[self checkForGlobalUsage: (tmethod allReferencedVariablesUsing: self) in: tmethod.
^nil].
self addMethod: tmethod.
"If the method has a macro then add the macro. But keep the method
for analysis purposes (e.g. its variable accesses)."
(method pragmaAt: #cmacro:) ifNotNil:
[:pragma|
self addMacro: (pragma argumentAt: 1) for: selector.
(inlineList includes: selector) ifTrue:
[inlineList := inlineList copyWithout: selector]].
(method pragmaAt: #cmacro) ifNotNil:
[:pragma| | literal | "Method should be just foo ^const"
self assert: (method numArgs = 0 and: [method numLiterals = 3 or: [method isQuick]]).
literal := method isQuick
ifTrue: [method decompile quickMethodReturnLiteral]
ifFalse: [method literalAt: 1].
self addMacro: '() ', (method isReturnField
ifTrue: [literal]
ifFalse: [self cLiteralFor: literal value name: method selector]) for: selector.
(inlineList includes: selector) ifTrue:
[inlineList := inlineList copyWithout: selector]].
^tmethod
]
{ #category : #public }
CCodeGenerator >> addMethodsForTranslatedPrimitives: classAndSelectorList [
| verbose |
verbose := false.
classAndSelectorList do:
[:classAndSelector | | aClass selector meth |
aClass := Smalltalk at: classAndSelector first.
selector := classAndSelector last.
self addAllClassVarsFor: aClass.
"compile the method source and convert to a suitable translation method.
find the method in either the class or the metaclass"
meth := self
compileToTMethodSelector: selector
in: ((aClass includesSelector: selector)
ifTrue: [aClass]
ifFalse: [aClass class]).
meth primitive > 0 ifTrue:
[meth preparePrimitiveName].
meth replaceSizeMessages.
self addMethod: meth].
self prepareMethods
]
{ #category : #public }
CCodeGenerator >> addPoolVarsFor: aClass [
"Add the pool variables for the given class to the code base as constants."
(aClass sharedPools reject: [:pool| pools includes: pool]) do:
[:pool |
pools add: pool.
pool bindingsDo:
[:binding |
self addConstantForBinding: binding]]
]
{ #category : #public }
CCodeGenerator >> addSelectorTranslation: aSelector to: aString [
selectorTranslations at: aSelector asSymbol put: aString
]
{ #category : #public }
CCodeGenerator >> addStructClass: aClass [
"Add the non-accessor methods of the given struct class to the code base."
aClass prepareToBeAddedToCodeGenerator: self.
self addClassVarsFor: aClass.
self addPoolVarsFor: aClass.
self retainMethods: (aClass requiredMethodNames: self options).
UIManager default
displayProgress: 'Adding Class ' , aClass name , '...'
from: 0
to: aClass selectors size
during:
[:bar |
aClass selectors doWithIndex:
[:sel :i | | source |
bar value: i.
self addStructMethodFor: aClass selector: sel]].
aClass declareCVarsIn: self
]
{ #category : #accessing }
CCodeGenerator >> addStructClasses: classes [
"Add the struct classes and save them for emitCTypesOn: later."
structClasses := classes.
structClasses do:
[:structClass|
(structClass withAllSuperclasses copyUpTo: VMStructType) do:
[:structClassOrSuperclass|
self addStructClass: structClassOrSuperclass]]
]
{ #category : #utilities }
CCodeGenerator >> addStructMethodFor: aClass selector: selector [
"Add the given struct method to the code base and answer its translation
or nil if it shouldn't be translated."
(self methodNamed: selector) ifNotNil:
[:tmethod|
"If we're repeating an attempt to add the same thing, or
if the existing method overrides this one,don't complain."
(tmethod definingClass includesBehavior: aClass) ifTrue:
[^self].
"If the methods are both simple accessors, don't complain."
((tmethod definingClass isAccessor: selector)
and: [aClass isAccessor: selector]) ifTrue:
[^self].
"If the method is overriding a method in a superclass, don't complain"
(aClass inheritsFrom: tmethod definingClass)
ifTrue: [methods removeKey: selector]
ifFalse: [self error: 'conflicting implementations for ', selector storeString]].
^(self addMethodFor: aClass selector: selector) ifNotNil:
[:tmethod|
tmethod transformToStructClassMethodFor: self.
tmethod]
]
{ #category : #utilities }
CCodeGenerator >> addVariablesInVerbatimCIn: aCCodeSendNode to: aCollection [
"If aCCodeSendNode has a string argument, parse it and extract anything
that looks like a variable, and add the resulting vars to aCollection."
| separators tokens |
(aCCodeSendNode isSend
and: [(aCCodeSendNode selector beginsWith: #cCode:)
and: [aCCodeSendNode args first isConstant
and: [aCCodeSendNode args first value isString]]]) ifFalse:
[^self].
separators := (Character space to: 255 asCharacter) reject:
[:char|
char isLetter or: [char isDigit or: [char = $_]]].
tokens := aCCodeSendNode args first value findTokens: separators.
aCollection addAll: (tokens select: [:token| token first isLetter]) asSet
]
{ #category : #utilities }
CCodeGenerator >> anyMethodNamed: selector [
"Answer any method in the code base (including api methods) with the given selector."
^methods
at: selector
ifAbsent:
[apiMethods ifNotNil:
[apiMethods
at: selector
ifAbsent: []]]
]
{ #category : #utilities }
CCodeGenerator >> arrayInitializerCalled: varName for: array sizeString: sizeStringOrNil type: cType [
"array is a literal array or a CArray on some array."
^String streamContents:
[:s| | sequence lastLine index newLine allIntegers |
sequence := array isCollection ifTrue: [array] ifFalse: [array object].
"this is to align -ve and +ve integers nicely in the primitiveAccessorDepthTable"
allIntegers := sequence allSatisfy: [:element| element isInteger].
lastLine := index := 0.
newLine := [sequence size >= 20
ifTrue: [s cr; nextPutAll: '/*'; print: index; nextPutAll: '*/'; tab]
ifFalse: [s crtab: 2].
lastLine := s position].
s nextPutAll: cType;
space;
nextPutAll: varName;
nextPut: $[.
sizeStringOrNil ifNotNil: [s nextPutAll: sizeStringOrNil].
s nextPutAll: '] = '.
sequence isString
ifTrue: [s nextPutAll: (self cLiteralFor: sequence)]
ifFalse:
[s nextPut: ${.
newLine value.
sequence
do: [:element|
(allIntegers
and: [element < 0
and: [s peekLast = Character space]]) ifTrue:
[s skip: -1].
s nextPutAll: (self cLiteralFor: element). index := index + 1]
separatedBy:
[s nextPut: $,.
((s position - lastLine) >= 76
or: [(index \\ 20) = 0])
ifTrue: [newLine value]
ifFalse: [s space]].
s crtab; nextPut: $}]]
]
{ #category : #utilities }
CCodeGenerator >> baseTypeForPointerType: aCType [
"Answer the type of the referent of a pointer type."
self assert: aCType last == $*.
^self baseTypeForType: aCType allButLast
]
{ #category : #utilities }
CCodeGenerator >> baseTypeForType: aCType [
"Reduce various declarations to the most basic type we can determine."
| type fpIndex closeidx openidx |
type := aCType.
((openidx := type indexOfSubCollection: 'const ') > 0
and: [openidx = 1 or: [(type at: openidx) isSeparator]]) ifTrue:
[type := type copyReplaceFrom: openidx to: openidx + 5 with: ''].
((type beginsWith: 'unsigned') and: [(type includes: $:) and: [type last isDigit]]) ifTrue:
[^#usqInt].
"collapse e.g. void (*foo(int bar))(void) to void (*)(void)"
(fpIndex := type indexOfSubCollection: '(*') > 0 ifTrue:
["elide the function arguments after *, if there are any"
type := type copyReplaceFrom: (type indexOf: $( startingAt: fpIndex + 1)
to: (type indexOf: $) startingAt: fpIndex + 1)
with: ''.
"elide the function name after *, if there is one"
type := type copyReplaceFrom: fpIndex + 2
to: (type indexOf: $) startingAt: fpIndex + 1)
with: ')'].
"collapse [size] to *"
openidx := 0.
[(openidx := type indexOf: $[ startingAt: openidx + 1) > 0
and: [(closeidx := type indexOf: $] startingAt: openidx + 1) > 0]] whileTrue:
[type := type copyReplaceFrom: openidx to: closeidx with: '*'].
"map foo* to foo *"
^self conventionalTypeForType: type
]
{ #category : #accessing }
CCodeGenerator >> breakDestInlineSelector: aSelector [
breakDestInlineSelectors add: aSelector
]
{ #category : #accessing }
CCodeGenerator >> breakOnInline: aBooleanOrNil [
breakOnInline := aBooleanOrNil
]
{ #category : #accessing }
CCodeGenerator >> breakSrcInlineSelector: aSelector [
breakSrcInlineSelectors add: aSelector
]
{ #category : #utilities }
CCodeGenerator >> cCodeForMethod: selector [
"Answer a string containing the C code for the given method."
"Example:
((CCodeGenerator new initialize addClass: TestCClass1; prepareMethods)
cCodeForMethod: #ifTests)"
| m s |
m := self methodNamed: selector.
m = nil ifTrue: [ self error: 'method not found in code base: ', selector ].
s := (ReadWriteStream on: '').
m emitCCodeOn: s generator: self.
^ s contents
]
{ #category : #'C code generator' }
CCodeGenerator >> cFunctionNameFor: aSelector [
"Create a C function name from the given selector by finding
a specific translation, or if none, simply omitting colons, and
any trailing underscores (this supports a varargs convention)."
^selectorTranslations
at: aSelector
ifAbsent:
[| cSelector |
cSelector := aSelector copyWithout: $:.
aSelector last = $: ifTrue:
[[cSelector last = $_] whileTrue:
[cSelector := cSelector allButLast]].
cSelector]
]
{ #category : #'C code generator' }
CCodeGenerator >> cLiteralFor: anObject [
"Return a string representing the C literal value for the given object."
anObject isNumber
ifTrue:
[anObject isInteger ifTrue:
[| hex |
hex := (anObject > 0
and: [(anObject >> anObject lowBit + 1) isPowerOfTwo
and: [(anObject highBit = anObject lowBit and: [anObject > 65536])
or: [anObject highBit - anObject lowBit >= 4]]]).
^self cLiteralForInteger: anObject hex: hex].
anObject isFloat ifTrue:
[^anObject printString]]
ifFalse:
[anObject isSymbol ifTrue:
[^self cFunctionNameFor: anObject].
anObject isString ifTrue:
[^'"', (anObject copyReplaceAll: (String with: Character cr) with: '\n') , '"'].
anObject == nil ifTrue: [^ 'null' ].
anObject == true ifTrue: [^ '1' ].
anObject == false ifTrue: [^ '0' ].
anObject isCharacter ifTrue:
[^anObject == $'
ifTrue: ['''\'''''] "i.e. '\''"
ifFalse: [anObject asString printString]]].
self error: 'Warning: A Smalltalk literal could not be translated into a C constant: ', anObject printString.
^'"XXX UNTRANSLATABLE CONSTANT XXX"'
]
{ #category : #'C code generator' }
CCodeGenerator >> cLiteralFor: anObject name: smalltalkName [
"Return a string representing the C literal value for the given object.
This version may use hex for integers that are bit masks."
anObject isInteger ifTrue:
[| hex dec useHexa |
hex := anObject printStringBase: 16.
dec := anObject printStringBase: 10.
useHexa := ((smalltalkName endsWith: 'Mask')
or: [anObject digitLength > 1
and: [(hex asSet size * 3) <= (dec asSet size * 2)
and: [(smalltalkName endsWith: 'Size') not]]]).
^self cLiteralForInteger: anObject hex: useHexa].
^self cLiteralFor: anObject
]
{ #category : #'C code generator' }
CCodeGenerator >> cLiteralForInteger: anInteger hex: aBoolean [
"Answer the string for generating a literal integer.
Use hexadecimal notation as prescribed by aBoolean.
Use long long suffix (LL) if the integer does not fit on 32 bits.
Use unsigned suffix (U) if the integer does not fit on a signed integer (resp. long long).
Correctly generate INT_MIN and LONG_LONG_MIN.
Indeed -0x8000000 is parsed as - (0x8000000) by C Compiler.
0x8000000 does not fit on a signed int, it is interpreted as unsigned.
That makes INT_MIN unsigned which is badly broken..."
| printString |
printString := aBoolean
ifTrue: [anInteger positive
ifTrue: ['0x' , (anInteger printStringBase: 16)]
ifFalse: ['-0x' , (anInteger negated printStringBase: 16)]]
ifFalse: [anInteger printString].
^anInteger positive
ifTrue: [anInteger > 16r7FFFFFFF "INT_MAX"
ifTrue: [anInteger > 16rFFFFFFFF "UINT_MAX"
ifTrue: [anInteger > 16r7FFFFFFFFFFFFFFF "LONG_LONG_MAX"
ifTrue: [printString , 'ULL']
ifFalse: [printString , 'LL']]
ifFalse: [printString , 'U']]
ifFalse: [printString]]
ifFalse: [anInteger < -16r8000000
ifTrue: [anInteger = -16r800000000000000 "LONG_LONG_MIN"
ifTrue: ['(-0x7FFFFFFFFFFFFFFFLL-1)']
ifFalse: [printString , 'LL']]
ifFalse: [anInteger = -16r8000000 "INT_MIN"
ifTrue: ['(-0x7FFFFFFF-1)']
ifFalse: [printString]]]
]
{ #category : #'C code generator' }
CCodeGenerator >> cLiteralForPrintfString: aString [
^(('"', (PrintfFormatString new setFormat: aString) transformForVMMaker, '"')
copyReplaceAll: (String with: Character cr) with: '\n')
copyReplaceAll: (String with: Character tab) with: '\t'
]
{ #category : #'C code generator' }
CCodeGenerator >> cLiteralForUnsignedInteger: anInteger hex: aBoolean longlong: llBoolean [
"Answer the string for generating an unsigned literal integer.
Use hexadecimal notation as prescribed by aBoolean.
Force long long suffix (LL) if the integer does not fit on 32 bits, or if llBoolean is true."
| printString |
printString := aBoolean
ifTrue: [anInteger positive
ifTrue: ['0x' , (anInteger printStringBase: 16)]
ifFalse: ['-0x' , (anInteger negated printStringBase: 16)]]
ifFalse: [anInteger printString].
^anInteger positive
ifTrue: [(llBoolean or: [anInteger > 16rFFFFFFFF "UINT_MAX"])
ifTrue: [printString , 'ULL']
ifFalse: [printString , 'U']]
ifFalse: [self error: 'please provide positive integer']
]
{ #category : #'C code generator' }
CCodeGenerator >> cLiteralForUnsignedInteger: anInteger longlong: llBoolean [
"Answer the string for generating an unsigned literal integer.
Eventually use hexadecimal.
Force long long suffix (LL) if the integer does not fit on 32 bits, or if llBoolean is true."
| hex |
hex := (anInteger > 0
and: [(anInteger >> anInteger lowBit + 1) isPowerOfTwo
and: [(anInteger highBit = anInteger lowBit and: [anInteger > 65536])
or: [anInteger highBit - anInteger lowBit >= 4]]]).
^self cLiteralForUnsignedInteger: anInteger hex: hex longlong: llBoolean
]
{ #category : #inlining }
CCodeGenerator >> cannotInline: selector [
self error: 'Failed to inline ', selector,
' as it contains unrenamable C declarations or C code'
]
{ #category : #'error notification' }
CCodeGenerator >> checkClassForNameConflicts: aClass [
"Verify that the given class does not have constant, variable, or method names that conflict with
those of previously added classes. Raise an error if a conflict is found, otherwise just return."
"check for constant name collisions in class pools"
aClass classPool associationsDo:
[:assoc |
(constants includesKey: assoc key) ifTrue:
[self error: 'Constant ', assoc key, ' was defined in a previously added class']].
"and in shared pools"
(aClass sharedPools reject: [:pool| pools includes: pool]) do:
[:pool |
pool bindingsDo:
[:assoc |
(constants includesKey: assoc key) ifTrue:
[self error: 'Constant ', assoc key, ' was defined in a previously added class']]].
"check for instance variable name collisions"
(aClass inheritsFrom: VMStructType) ifFalse:
[(self instVarNamesForClass: aClass) do:
[:varName |
(variables includes: varName) ifTrue:
[self error: 'Instance variable ', varName, ' was defined in a previously added class']]].
"check for method name collisions"
aClass selectors do:
[:sel | | tmeth meth |
((self shouldIncludeMethodFor: aClass selector: sel)
and: [(tmeth := methods at: sel ifAbsent: nil) notNil
and: [(aClass isStructClass and: [(aClass isAccessor: sel)
and: [(methods at: sel) isStructAccessor]]) not
and: [(meth := aClass >> sel) isSubclassResponsibility not
and: [(aClass includesBehavior: tmeth definingClass) not]]]]) ifTrue:
[((aClass >>sel) pragmaAt: #option:)
ifNil: [self error: 'Method ', sel, ' was defined in a previously added class.']
ifNotNil:
[logger
ensureCr;
show: 'warning, method ', aClass name, '>>', sel storeString,
' overrides ', tmeth definingClass, '>>', sel storeString;
cr]]]
]
{ #category : #utilities }
CCodeGenerator >> checkDeleteVariable: aName [
"Hook for debugging variable deletion."
]
{ #category : #utilities }
CCodeGenerator >> checkForGlobalUsage: vars in: aTMethod [
vars do:
[:var |
(variables includes: var) ifTrue: "find the set of method names using this global var"
[(globalVariableUsage at: var ifAbsentPut: [Set new])
add: aTMethod selector]].
aTMethod clearReferencesToGlobalStruct.
(aTMethod locals select: [:l| self reservedWords includes: l]) do:
[:l| | em |
em := aTMethod definingClass name, '>>', aTMethod smalltalkSelector, ' has variable that is a C reserved word: ', l.
self error: em.
self logger cr; nextPutAll: em; cr; flush]
]
{ #category : #public }
CCodeGenerator >> codeString [
"Return a string containing all the C code for the code base. Used for testing."
| stream |
stream := ReadWriteStream on: (String new: 1000).
self emitCCodeOn: stream doInlining: true doAssertions: true.
^stream contents
]
{ #category : #inlining }
CCodeGenerator >> collectInlineList: strategy [
"Make a list of methods that should be inlined. If inlineFlagOrSymbol == #asSpecified
only inline methods marked with <inline: true>. If inlineFlagOrSymbol == #asSpecifiedOrQuick
only inline methods marked with <inline: true> or methods that are quick (^constant, ^inst var)."
"Details: The method must not include any inline C, since the
translator cannot currently map variable names in inlined C code.
Methods to be inlined must be small or called from only one place."
| selectorsOfMethodsNotToInline callsOf inlineStrategy |
inlineStrategy := strategy asCCodeInlineStrategy.
inlineStrategy codeGenerator: self.
selectorsOfMethodsNotToInline := Set new: methods size.
selectorsOfMethodsNotToInline addAll: macros keys.
apiMethods ifNotNil: [ selectorsOfMethodsNotToInline addAll: apiMethods keys ].
selectorsOfMethodsNotToInline addAll: self structAccessorSelectors.
"build dictionary to record the number of calls to each method"
callsOf := Dictionary new: methods size * 2.
methods keysAndValuesDo:
[:s :m|
(m isRealMethod
and: [self shouldGenerateMethod: m]) ifTrue:
[callsOf at: s put: 0]].
"For each method, scan its parse tree once or twice to:
1. determine if the method contains unrenamable C code or declarations or has a C builtin
2. determine how many nodes it has
3. increment the sender counts of the methods it calls"
inlineList := Set new: methods size * 2.
methods
reject: [:m|
(selectorsOfMethodsNotToInline includes: m selector)
or: [ self isSpecialSelector: m selector ] ]
thenDo: [:m|
m parseTree nodesDo: [:node|
node isSend ifTrue: [
callsOf
at: node selector
ifPresent: [:senderCount| callsOf at: node selector put: senderCount + 1 ] ] ].
inlineStrategy validateCanInline: m.
(inlineStrategy canInline: m)
ifFalse: [ selectorsOfMethodsNotToInline add: m selector ]
ifTrue: [
(inlineStrategy shouldInlineMethod: m)
ifTrue: [
"inline if method has no C code and is either small or contains inline directive"
inlineList add: m selector]
ifFalse: [
inlineStrategy isSelectiveInlineStrategy
ifTrue: [selectorsOfMethodsNotToInline add: m selector] ] ] ].
inlineStrategy isSelectiveInlineStrategy
ifTrue:
[methods do: [:m| m inline ifNil: [m inline: (inlineList includes: m selector)]]]
ifFalse:
[callsOf associationsDo:
[:assoc|
(assoc value = 1
and: [(selectorsOfMethodsNotToInline includes: assoc key) not]) ifTrue:
[ inlineList add: assoc key ]]]
]
{ #category : #utilities }
CCodeGenerator >> compileToTMethodSelector: selector in: aClass [
"Compile a method to a TMethod"
^(aClass >> selector) asTranslationMethodOfClass: self translationMethodClass
"was:
| implementingClass |
implementingClass := aClass.
^(Compiler new
parse: ([aClass sourceCodeAt: selector]
on: KeyNotFound
do: [:ex| ""Quick hack for simulating Pharo images...""
(PharoVM and: [aClass == String class and: [selector == #findSubstringViaPrimitive:in:startingAt:matchTable:]]) ifFalse:
[ex pass].
(implementingClass := ByteString) sourceCodeAt: #findSubstring:in:startingAt:matchTable:])
in: implementingClass
notifying: nil)
asTranslationMethodOfClass: self translationMethodClass"
]
{ #category : #public }
CCodeGenerator >> computeKernelReturnTypes [
| dictionary |
dictionary := Dictionary newFromPairs:
#(oopAt: #sqInt oopAt:put: #sqInt
oopAtPointer: #sqInt oopAtPointer:put: #sqInt
byteAt: #sqInt byteAt:put: #sqInt
byteAtPointer: #sqInt byteAtPointer:put: #sqInt
shortAt: #sqInt shortAt:put: #sqInt
shortAtPointer: #sqInt shortAtPointer:put: #sqInt
intAt: #sqInt intAt:put: #sqInt
intAtPointer: #sqInt intAtPointer:put: #sqInt
longAt: #sqInt longAt:put: #sqInt
longAtPointer: #sqInt longAtPointer:put: #sqInt
long32At: #int long32At:put: #int
unalignedLongAt: #sqInt unalignedLongAt:put: #sqInt
unalignedLong32At: #int unalignedLong32At:put: #int
long64At: #sqLong long64At:put: #sqLong
long64AtPointer: #sqLong long64AtPointer:put: #sqLong
singleFloatAtPointer: #float singleFloatAtPointerPut: #float
floatAtPointer: #double floatAtPointerPut: #double
fetchFloatAt:into: #void storeFloatAt:from: #void
fetchFloatAtPointer:into: #void storeFloatAtPointer:from: #void
fetchSingleFloatAt:into: #void storeSingleFloatAt:from: #void
fetchSingleFloatAtPointer:into: #void storeSingleFloatAtPointer:from: #void
pointerForOop: #'char *' oopForPointer: #sqInt
baseHeaderSize #sqInt wordSize #sqInt bytesPerOop #sqInt).