1/*
2 * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23package org.graalvm.compiler.hotspot;
24
25import java.nio.ByteBuffer;
26import java.nio.ByteOrder;
27import java.util.ArrayList;
28import java.util.Collections;
29import java.util.Comparator;
30import java.util.EnumMap;
31import java.util.List;
32import java.util.Map;
33import java.util.stream.Stream;
34import java.util.stream.Stream.Builder;
35
36import org.graalvm.compiler.code.CompilationResult;
37import org.graalvm.compiler.code.CompilationResult.CodeAnnotation;
38import org.graalvm.compiler.code.CompilationResult.CodeComment;
39import org.graalvm.compiler.code.CompilationResult.JumpTable;
40import org.graalvm.compiler.debug.GraalError;
41import org.graalvm.compiler.code.DataSection;
42import org.graalvm.compiler.code.SourceMapping;
43import org.graalvm.compiler.graph.NodeSourcePosition;
44
45import jdk.vm.ci.code.CodeCacheProvider;
46import jdk.vm.ci.code.DebugInfo;
47import jdk.vm.ci.code.StackSlot;
48import jdk.vm.ci.code.site.ConstantReference;
49import jdk.vm.ci.code.site.DataPatch;
50import jdk.vm.ci.code.site.Infopoint;
51import jdk.vm.ci.code.site.InfopointReason;
52import jdk.vm.ci.code.site.Mark;
53import jdk.vm.ci.code.site.Site;
54import jdk.vm.ci.hotspot.HotSpotCompilationRequest;
55import jdk.vm.ci.hotspot.HotSpotCompiledCode;
56import jdk.vm.ci.hotspot.HotSpotCompiledCode.Comment;
57import jdk.vm.ci.hotspot.HotSpotCompiledNmethod;
58import jdk.vm.ci.hotspot.HotSpotObjectConstant;
59import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod;
60import jdk.vm.ci.meta.Assumptions.Assumption;
61import jdk.vm.ci.meta.ResolvedJavaMethod;
62
63public class HotSpotCompiledCodeBuilder {
64
65    public static HotSpotCompiledCode createCompiledCode(CodeCacheProvider codeCache, ResolvedJavaMethod method, HotSpotCompilationRequest compRequest, CompilationResult compResult) {
66        String name = compResult.getName();
67
68        byte[] targetCode = compResult.getTargetCode();
69        int targetCodeSize = compResult.getTargetCodeSize();
70
71        Site[] sites = getSortedSites(codeCache, compResult);
72
73        Assumption[] assumptions = compResult.getAssumptions();
74
75        ResolvedJavaMethod[] methods = compResult.getMethods();
76
77        List<CodeAnnotation> annotations = compResult.getAnnotations();
78        Comment[] comments = new Comment[annotations.size()];
79        if (!annotations.isEmpty()) {
80            for (int i = 0; i < comments.length; i++) {
81                CodeAnnotation annotation = annotations.get(i);
82                String text;
83                if (annotation instanceof CodeComment) {
84                    CodeComment codeComment = (CodeComment) annotation;
85                    text = codeComment.value;
86                } else if (annotation instanceof JumpTable) {
87                    JumpTable jumpTable = (JumpTable) annotation;
88                    text = "JumpTable [" + jumpTable.low + " .. " + jumpTable.high + "]";
89                } else {
90                    text = annotation.toString();
91                }
92                comments[i] = new Comment(annotation.position, text);
93            }
94        }
95
96        DataSection data = compResult.getDataSection();
97        byte[] dataSection = new byte[data.getSectionSize()];
98
99        ByteBuffer buffer = ByteBuffer.wrap(dataSection).order(ByteOrder.nativeOrder());
100        Builder<DataPatch> patchBuilder = Stream.builder();
101        data.buildDataSection(buffer, vmConstant -> {
102            patchBuilder.accept(new DataPatch(buffer.position(), new ConstantReference(vmConstant)));
103        });
104
105        int dataSectionAlignment = data.getSectionAlignment();
106        DataPatch[] dataSectionPatches = patchBuilder.build().toArray(len -> new DataPatch[len]);
107
108        int totalFrameSize = compResult.getTotalFrameSize();
109        StackSlot customStackArea = compResult.getCustomStackArea();
110        boolean isImmutablePIC = compResult.isImmutablePIC();
111
112        if (method instanceof HotSpotResolvedJavaMethod) {
113            HotSpotResolvedJavaMethod hsMethod = (HotSpotResolvedJavaMethod) method;
114            int entryBCI = compResult.getEntryBCI();
115            boolean hasUnsafeAccess = compResult.hasUnsafeAccess();
116
117            int id;
118            long jvmciEnv;
119            if (compRequest != null) {
120                id = compRequest.getId();
121                jvmciEnv = compRequest.getJvmciEnv();
122            } else {
123                id = hsMethod.allocateCompileId(entryBCI);
124                jvmciEnv = 0L;
125            }
126            return new HotSpotCompiledNmethod(name, targetCode, targetCodeSize, sites, assumptions, methods, comments, dataSection, dataSectionAlignment, dataSectionPatches, isImmutablePIC,
127                            totalFrameSize, customStackArea, hsMethod, entryBCI, id, jvmciEnv, hasUnsafeAccess);
128        } else {
129            return new HotSpotCompiledCode(name, targetCode, targetCodeSize, sites, assumptions, methods, comments, dataSection, dataSectionAlignment, dataSectionPatches, isImmutablePIC,
130                            totalFrameSize, customStackArea);
131        }
132    }
133
134    static class SiteComparator implements Comparator<Site> {
135
136        /**
137         * Defines an order for sorting {@link Infopoint}s based on their
138         * {@linkplain Infopoint#reason reasons}. This is used to choose which infopoint to preserve
139         * when multiple infopoints collide on the same PC offset. A negative order value implies a
140         * non-optional infopoint (i.e., must be preserved).
141         */
142        static final Map<InfopointReason, Integer> HOTSPOT_INFOPOINT_SORT_ORDER = new EnumMap<>(InfopointReason.class);
143
144        static {
145            HOTSPOT_INFOPOINT_SORT_ORDER.put(InfopointReason.SAFEPOINT, -4);
146            HOTSPOT_INFOPOINT_SORT_ORDER.put(InfopointReason.CALL, -3);
147            HOTSPOT_INFOPOINT_SORT_ORDER.put(InfopointReason.IMPLICIT_EXCEPTION, -2);
148            HOTSPOT_INFOPOINT_SORT_ORDER.put(InfopointReason.METHOD_START, 2);
149            HOTSPOT_INFOPOINT_SORT_ORDER.put(InfopointReason.METHOD_END, 3);
150            HOTSPOT_INFOPOINT_SORT_ORDER.put(InfopointReason.BYTECODE_POSITION, 4);
151        }
152
153        static int ord(Infopoint info) {
154            return HOTSPOT_INFOPOINT_SORT_ORDER.get(info.reason);
155        }
156
157        static int checkCollision(Infopoint i1, Infopoint i2) {
158            int o1 = ord(i1);
159            int o2 = ord(i2);
160            if (o1 < 0 && o2 < 0) {
161                throw new GraalError("Non optional infopoints cannot collide: %s and %s", i1, i2);
162            }
163            return o1 - o2;
164        }
165
166        /**
167         * Records whether any two {@link Infopoint}s had the same {@link Infopoint#pcOffset}.
168         */
169        boolean sawCollidingInfopoints;
170
171        @Override
172        public int compare(Site s1, Site s2) {
173            if (s1.pcOffset == s2.pcOffset) {
174                // Marks must come first since patching a call site
175                // may need to know the mark denoting the call type
176                // (see uses of CodeInstaller::_next_call_type).
177                boolean s1IsMark = s1 instanceof Mark;
178                boolean s2IsMark = s2 instanceof Mark;
179                if (s1IsMark != s2IsMark) {
180                    return s1IsMark ? -1 : 1;
181                }
182
183                // Infopoints must group together so put them after
184                // other Site types.
185                boolean s1IsInfopoint = s1 instanceof Infopoint;
186                boolean s2IsInfopoint = s2 instanceof Infopoint;
187                if (s1IsInfopoint != s2IsInfopoint) {
188                    return s1IsInfopoint ? 1 : -1;
189                }
190
191                if (s1IsInfopoint) {
192                    sawCollidingInfopoints = true;
193                    return checkCollision((Infopoint) s1, (Infopoint) s2);
194                }
195            }
196            return s1.pcOffset - s2.pcOffset;
197        }
198    }
199
200    /**
201     * HotSpot expects sites to be presented in ascending order of PC (see
202     * {@code DebugInformationRecorder::add_new_pc_offset}). In addition, it expects
203     * {@link Infopoint} PCs to be unique.
204     */
205    private static Site[] getSortedSites(CodeCacheProvider codeCache, CompilationResult target) {
206        List<Site> sites = new ArrayList<>(
207                        target.getExceptionHandlers().size() + target.getInfopoints().size() + target.getDataPatches().size() + target.getMarks().size() + target.getSourceMappings().size());
208        sites.addAll(target.getExceptionHandlers());
209        sites.addAll(target.getInfopoints());
210        sites.addAll(target.getDataPatches());
211        sites.addAll(target.getMarks());
212
213        /*
214         * Translate the source mapping into appropriate info points. In HotSpot only one position
215         * can really be represented and recording the end PC seems to give the best results and
216         * corresponds with what C1 and C2 do.
217         */
218        if (codeCache.shouldDebugNonSafepoints()) {
219            for (SourceMapping source : target.getSourceMappings()) {
220                sites.add(new Infopoint(source.getEndOffset(), new DebugInfo(source.getSourcePosition()), InfopointReason.BYTECODE_POSITION));
221                assert verifySourcePositionReceivers(source.getSourcePosition());
222            }
223        }
224
225        SiteComparator c = new SiteComparator();
226        Collections.sort(sites, c);
227        if (c.sawCollidingInfopoints) {
228            Infopoint lastInfopoint = null;
229            List<Site> copy = new ArrayList<>(sites.size());
230            for (Site site : sites) {
231                if (site instanceof Infopoint) {
232                    Infopoint info = (Infopoint) site;
233                    if (lastInfopoint == null || lastInfopoint.pcOffset != info.pcOffset) {
234                        lastInfopoint = info;
235                        copy.add(info);
236                    } else {
237                        // Omit this colliding infopoint
238                        assert lastInfopoint.reason.compareTo(info.reason) <= 0;
239                    }
240                } else {
241                    copy.add(site);
242                }
243            }
244            sites = copy;
245        }
246        return sites.toArray(new Site[sites.size()]);
247    }
248
249    /**
250     * Verifies that the captured receiver type agrees with the declared type of the method.
251     */
252    private static boolean verifySourcePositionReceivers(NodeSourcePosition start) {
253        NodeSourcePosition pos = start;
254        while (pos != null) {
255            if (pos.getReceiver() != null) {
256                assert ((HotSpotObjectConstant) pos.getReceiver()).asObject(pos.getMethod().getDeclaringClass()) != null;
257            }
258            pos = pos.getCaller();
259        }
260        return true;
261    }
262}
263