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.amd64;
24
25import static jdk.vm.ci.amd64.AMD64.r10;
26import static jdk.vm.ci.amd64.AMD64.rax;
27import static jdk.vm.ci.amd64.AMD64.rsp;
28import static jdk.vm.ci.code.ValueUtil.asRegister;
29import static org.graalvm.compiler.core.common.GraalOptions.CanOmitFrame;
30import static org.graalvm.compiler.core.common.GraalOptions.GeneratePIC;
31import static org.graalvm.compiler.core.common.GraalOptions.ZapStackOnMethodEntry;
32
33import org.graalvm.compiler.asm.Assembler;
34import org.graalvm.compiler.asm.Label;
35import org.graalvm.compiler.asm.amd64.AMD64Address;
36import org.graalvm.compiler.asm.amd64.AMD64Assembler.ConditionFlag;
37import org.graalvm.compiler.asm.amd64.AMD64MacroAssembler;
38import org.graalvm.compiler.code.CompilationResult;
39import org.graalvm.compiler.core.amd64.AMD64NodeMatchRules;
40import org.graalvm.compiler.core.common.CompilationIdentifier;
41import org.graalvm.compiler.core.common.LIRKind;
42import org.graalvm.compiler.core.common.alloc.RegisterAllocationConfig;
43import org.graalvm.compiler.core.target.Backend;
44import org.graalvm.compiler.debug.DebugContext;
45import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig;
46import org.graalvm.compiler.hotspot.HotSpotDataBuilder;
47import org.graalvm.compiler.hotspot.HotSpotGraalRuntimeProvider;
48import org.graalvm.compiler.hotspot.HotSpotHostBackend;
49import org.graalvm.compiler.hotspot.HotSpotLIRGenerationResult;
50import org.graalvm.compiler.hotspot.meta.HotSpotConstantLoadAction;
51import org.graalvm.compiler.hotspot.meta.HotSpotForeignCallsProvider;
52import org.graalvm.compiler.hotspot.meta.HotSpotProviders;
53import org.graalvm.compiler.hotspot.stubs.Stub;
54import org.graalvm.compiler.lir.LIR;
55import org.graalvm.compiler.lir.amd64.AMD64Call;
56import org.graalvm.compiler.lir.amd64.AMD64FrameMap;
57import org.graalvm.compiler.lir.amd64.AMD64FrameMapBuilder;
58import org.graalvm.compiler.lir.asm.CompilationResultBuilder;
59import org.graalvm.compiler.lir.asm.CompilationResultBuilderFactory;
60import org.graalvm.compiler.lir.asm.DataBuilder;
61import org.graalvm.compiler.lir.asm.FrameContext;
62import org.graalvm.compiler.lir.framemap.FrameMap;
63import org.graalvm.compiler.lir.framemap.FrameMapBuilder;
64import org.graalvm.compiler.lir.gen.LIRGenerationResult;
65import org.graalvm.compiler.lir.gen.LIRGeneratorTool;
66import org.graalvm.compiler.nodes.StructuredGraph;
67import org.graalvm.compiler.nodes.spi.NodeLIRBuilderTool;
68import org.graalvm.compiler.options.OptionValues;
69import org.graalvm.util.EconomicSet;
70
71import jdk.vm.ci.amd64.AMD64;
72import jdk.vm.ci.amd64.AMD64Kind;
73import jdk.vm.ci.code.CallingConvention;
74import jdk.vm.ci.code.Register;
75import jdk.vm.ci.code.RegisterConfig;
76import jdk.vm.ci.code.StackSlot;
77import jdk.vm.ci.hotspot.HotSpotCallingConventionType;
78import jdk.vm.ci.hotspot.HotSpotSentinelConstant;
79import jdk.vm.ci.meta.JavaKind;
80import jdk.vm.ci.meta.JavaType;
81import jdk.vm.ci.meta.ResolvedJavaMethod;
82
83/**
84 * HotSpot AMD64 specific backend.
85 */
86public class AMD64HotSpotBackend extends HotSpotHostBackend {
87
88    public AMD64HotSpotBackend(GraalHotSpotVMConfig config, HotSpotGraalRuntimeProvider runtime, HotSpotProviders providers) {
89        super(config, runtime, providers);
90    }
91
92    @Override
93    public FrameMapBuilder newFrameMapBuilder(RegisterConfig registerConfig) {
94        RegisterConfig registerConfigNonNull = registerConfig == null ? getCodeCache().getRegisterConfig() : registerConfig;
95        return new AMD64FrameMapBuilder(newFrameMap(registerConfigNonNull), getCodeCache(), registerConfigNonNull);
96    }
97
98    @Override
99    public FrameMap newFrameMap(RegisterConfig registerConfig) {
100        return new AMD64FrameMap(getCodeCache(), registerConfig, this);
101    }
102
103    @Override
104    public LIRGeneratorTool newLIRGenerator(LIRGenerationResult lirGenRes) {
105        return new AMD64HotSpotLIRGenerator(getProviders(), config, lirGenRes);
106    }
107
108    @Override
109    public LIRGenerationResult newLIRGenerationResult(CompilationIdentifier compilationId, LIR lir, FrameMapBuilder frameMapBuilder, StructuredGraph graph, Object stub) {
110        return new HotSpotLIRGenerationResult(compilationId, lir, frameMapBuilder, makeCallingConvention(graph, (Stub) stub), stub);
111    }
112
113    @Override
114    public NodeLIRBuilderTool newNodeLIRBuilder(StructuredGraph graph, LIRGeneratorTool lirGen) {
115        return new AMD64HotSpotNodeLIRBuilder(graph, lirGen, new AMD64NodeMatchRules(lirGen));
116    }
117
118    @Override
119    protected void bangStackWithOffset(CompilationResultBuilder crb, int bangOffset) {
120        AMD64MacroAssembler asm = (AMD64MacroAssembler) crb.asm;
121        int pos = asm.position();
122        asm.movl(new AMD64Address(rsp, -bangOffset), AMD64.rax);
123        assert asm.position() - pos >= PATCHED_VERIFIED_ENTRY_POINT_INSTRUCTION_SIZE;
124    }
125
126    /**
127     * The size of the instruction used to patch the verified entry point of an nmethod when the
128     * nmethod is made non-entrant or a zombie (e.g. during deopt or class unloading). The first
129     * instruction emitted at an nmethod's verified entry point must be at least this length to
130     * ensure mt-safe patching.
131     */
132    public static final int PATCHED_VERIFIED_ENTRY_POINT_INSTRUCTION_SIZE = 5;
133
134    /**
135     * Emits code at the verified entry point and return point(s) of a method.
136     */
137    class HotSpotFrameContext implements FrameContext {
138
139        final boolean isStub;
140        final boolean omitFrame;
141
142        HotSpotFrameContext(boolean isStub, boolean omitFrame) {
143            this.isStub = isStub;
144            this.omitFrame = omitFrame;
145        }
146
147        @Override
148        public boolean hasFrame() {
149            return !omitFrame;
150        }
151
152        @Override
153        public void enter(CompilationResultBuilder crb) {
154            FrameMap frameMap = crb.frameMap;
155            int frameSize = frameMap.frameSize();
156            AMD64MacroAssembler asm = (AMD64MacroAssembler) crb.asm;
157            if (omitFrame) {
158                if (!isStub) {
159                    asm.nop(PATCHED_VERIFIED_ENTRY_POINT_INSTRUCTION_SIZE);
160                }
161            } else {
162                int verifiedEntryPointOffset = asm.position();
163                if (!isStub) {
164                    emitStackOverflowCheck(crb);
165                    // assert asm.position() - verifiedEntryPointOffset >=
166                    // PATCHED_VERIFIED_ENTRY_POINT_INSTRUCTION_SIZE;
167                }
168                if (!isStub && asm.position() == verifiedEntryPointOffset) {
169                    asm.subqWide(rsp, frameSize);
170                    assert asm.position() - verifiedEntryPointOffset >= PATCHED_VERIFIED_ENTRY_POINT_INSTRUCTION_SIZE;
171                } else {
172                    asm.decrementq(rsp, frameSize);
173                }
174                if (ZapStackOnMethodEntry.getValue(crb.getOptions())) {
175                    final int intSize = 4;
176                    for (int i = 0; i < frameSize / intSize; ++i) {
177                        asm.movl(new AMD64Address(rsp, i * intSize), 0xC1C1C1C1);
178                    }
179                }
180                assert frameMap.getRegisterConfig().getCalleeSaveRegisters() == null;
181            }
182        }
183
184        @Override
185        public void leave(CompilationResultBuilder crb) {
186            if (!omitFrame) {
187                AMD64MacroAssembler asm = (AMD64MacroAssembler) crb.asm;
188                assert crb.frameMap.getRegisterConfig().getCalleeSaveRegisters() == null;
189
190                int frameSize = crb.frameMap.frameSize();
191                asm.incrementq(rsp, frameSize);
192            }
193        }
194    }
195
196    @Override
197    protected Assembler createAssembler(FrameMap frameMap) {
198        return new AMD64MacroAssembler(getTarget());
199    }
200
201    @Override
202    public CompilationResultBuilder newCompilationResultBuilder(LIRGenerationResult lirGenRen, FrameMap frameMap, CompilationResult compilationResult, CompilationResultBuilderFactory factory) {
203        // Omit the frame if the method:
204        // - has no spill slots or other slots allocated during register allocation
205        // - has no callee-saved registers
206        // - has no incoming arguments passed on the stack
207        // - has no deoptimization points
208        // - makes no foreign calls (which require an aligned stack)
209        HotSpotLIRGenerationResult gen = (HotSpotLIRGenerationResult) lirGenRen;
210        LIR lir = gen.getLIR();
211        assert gen.getDeoptimizationRescueSlot() == null || frameMap.frameNeedsAllocating() : "method that can deoptimize must have a frame";
212        OptionValues options = lir.getOptions();
213        DebugContext debug = lir.getDebug();
214        boolean omitFrame = CanOmitFrame.getValue(options) && !frameMap.frameNeedsAllocating() && !lir.hasArgInCallerFrame() && !gen.hasForeignCall();
215
216        Stub stub = gen.getStub();
217        Assembler masm = createAssembler(frameMap);
218        HotSpotFrameContext frameContext = new HotSpotFrameContext(stub != null, omitFrame);
219        DataBuilder dataBuilder = new HotSpotDataBuilder(getCodeCache().getTarget());
220        CompilationResultBuilder crb = factory.createBuilder(getCodeCache(), getForeignCalls(), frameMap, masm, dataBuilder, frameContext, options, debug, compilationResult);
221        crb.setTotalFrameSize(frameMap.totalFrameSize());
222        crb.setMaxInterpreterFrameSize(gen.getMaxInterpreterFrameSize());
223        StackSlot deoptimizationRescueSlot = gen.getDeoptimizationRescueSlot();
224        if (deoptimizationRescueSlot != null && stub == null) {
225            crb.compilationResult.setCustomStackAreaOffset(deoptimizationRescueSlot);
226        }
227
228        if (stub != null) {
229            EconomicSet<Register> destroyedCallerRegisters = gatherDestroyedCallerRegisters(lir);
230            updateStub(stub, destroyedCallerRegisters, gen.getCalleeSaveInfo(), frameMap);
231        }
232
233        return crb;
234    }
235
236    @Override
237    public void emitCode(CompilationResultBuilder crb, LIR lir, ResolvedJavaMethod installedCodeOwner) {
238        AMD64MacroAssembler asm = (AMD64MacroAssembler) crb.asm;
239        FrameMap frameMap = crb.frameMap;
240        RegisterConfig regConfig = frameMap.getRegisterConfig();
241        Label verifiedEntry = new Label();
242
243        // Emit the prefix
244        emitCodePrefix(installedCodeOwner, crb, asm, regConfig, verifiedEntry);
245
246        // Emit code for the LIR
247        emitCodeBody(installedCodeOwner, crb, lir);
248
249        // Emit the suffix
250        emitCodeSuffix(installedCodeOwner, crb, asm, frameMap);
251
252        // Profile assembler instructions
253        profileInstructions(lir, crb);
254    }
255
256    /**
257     * Emits the code prior to the verified entry point.
258     *
259     * @param installedCodeOwner see {@link Backend#emitCode}
260     */
261    public void emitCodePrefix(ResolvedJavaMethod installedCodeOwner, CompilationResultBuilder crb, AMD64MacroAssembler asm, RegisterConfig regConfig, Label verifiedEntry) {
262        HotSpotProviders providers = getProviders();
263        if (installedCodeOwner != null && !installedCodeOwner.isStatic()) {
264            crb.recordMark(config.MARKID_UNVERIFIED_ENTRY);
265            CallingConvention cc = regConfig.getCallingConvention(HotSpotCallingConventionType.JavaCallee, null, new JavaType[]{providers.getMetaAccess().lookupJavaType(Object.class)}, this);
266            Register inlineCacheKlass = rax; // see definition of IC_Klass in
267                                             // c1_LIRAssembler_x86.cpp
268            Register receiver = asRegister(cc.getArgument(0));
269            AMD64Address src = new AMD64Address(receiver, config.hubOffset);
270
271            if (config.useCompressedClassPointers) {
272                Register register = r10;
273                AMD64HotSpotMove.decodeKlassPointer(crb, asm, register, providers.getRegisters().getHeapBaseRegister(), src, config);
274                if (GeneratePIC.getValue(crb.getOptions())) {
275                    asm.movq(providers.getRegisters().getHeapBaseRegister(), asm.getPlaceholder(-1));
276                    crb.recordMark(config.MARKID_NARROW_OOP_BASE_ADDRESS);
277                } else {
278                    if (config.narrowKlassBase != 0) {
279                        // The heap base register was destroyed above, so restore it
280                        asm.movq(providers.getRegisters().getHeapBaseRegister(), config.narrowOopBase);
281                    }
282                }
283                asm.cmpq(inlineCacheKlass, register);
284            } else {
285                asm.cmpq(inlineCacheKlass, src);
286            }
287            AMD64Call.directConditionalJmp(crb, asm, getForeignCalls().lookupForeignCall(IC_MISS_HANDLER), ConditionFlag.NotEqual);
288        }
289
290        asm.align(config.codeEntryAlignment);
291        crb.recordMark(config.MARKID_OSR_ENTRY);
292        asm.bind(verifiedEntry);
293        crb.recordMark(config.MARKID_VERIFIED_ENTRY);
294
295        if (GeneratePIC.getValue(crb.getOptions())) {
296            // Check for method state
297            HotSpotFrameContext frameContext = (HotSpotFrameContext) crb.frameContext;
298            if (!frameContext.isStub) {
299                crb.recordInlineDataInCodeWithNote(new HotSpotSentinelConstant(LIRKind.value(AMD64Kind.QWORD), JavaKind.Long), HotSpotConstantLoadAction.MAKE_NOT_ENTRANT);
300                asm.movq(AMD64.rax, asm.getPlaceholder(-1));
301                asm.testq(AMD64.rax, AMD64.rax);
302                AMD64Call.directConditionalJmp(crb, asm, getForeignCalls().lookupForeignCall(WRONG_METHOD_HANDLER), ConditionFlag.NotZero);
303            }
304        }
305    }
306
307    /**
308     * Emits the code which starts at the verified entry point.
309     *
310     * @param installedCodeOwner see {@link Backend#emitCode}
311     */
312    public void emitCodeBody(ResolvedJavaMethod installedCodeOwner, CompilationResultBuilder crb, LIR lir) {
313        crb.emit(lir);
314    }
315
316    /**
317     * @param installedCodeOwner see {@link Backend#emitCode}
318     */
319    public void emitCodeSuffix(ResolvedJavaMethod installedCodeOwner, CompilationResultBuilder crb, AMD64MacroAssembler asm, FrameMap frameMap) {
320        HotSpotProviders providers = getProviders();
321        HotSpotFrameContext frameContext = (HotSpotFrameContext) crb.frameContext;
322        if (!frameContext.isStub) {
323            HotSpotForeignCallsProvider foreignCalls = providers.getForeignCalls();
324            crb.recordMark(config.MARKID_EXCEPTION_HANDLER_ENTRY);
325            AMD64Call.directCall(crb, asm, foreignCalls.lookupForeignCall(EXCEPTION_HANDLER), null, false, null);
326            crb.recordMark(config.MARKID_DEOPT_HANDLER_ENTRY);
327            AMD64Call.directCall(crb, asm, foreignCalls.lookupForeignCall(DEOPTIMIZATION_HANDLER), null, false, null);
328        } else {
329            // No need to emit the stubs for entries back into the method since
330            // it has no calls that can cause such "return" entries
331
332            if (frameContext.omitFrame) {
333                // Cannot access slots in caller's frame if my frame is omitted
334                assert !frameMap.accessesCallerFrame();
335            }
336        }
337    }
338
339    @Override
340    public RegisterAllocationConfig newRegisterAllocationConfig(RegisterConfig registerConfig, String[] allocationRestrictedTo) {
341        RegisterConfig registerConfigNonNull = registerConfig == null ? getCodeCache().getRegisterConfig() : registerConfig;
342        return new AMD64HotSpotRegisterAllocationConfig(registerConfigNonNull, allocationRestrictedTo);
343    }
344
345    @Override
346    public EconomicSet<Register> translateToCallerRegisters(EconomicSet<Register> calleeRegisters) {
347        return calleeRegisters;
348    }
349}
350