codegen_test.cc revision 6e332529c33be4d7dae5dad3609a839f4c0d3bfc
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <functional>
18
19#include "arch/instruction_set.h"
20#include "arch/arm/instruction_set_features_arm.h"
21#include "arch/arm/registers_arm.h"
22#include "arch/arm64/instruction_set_features_arm64.h"
23#include "arch/mips/instruction_set_features_mips.h"
24#include "arch/mips/registers_mips.h"
25#include "arch/mips64/instruction_set_features_mips64.h"
26#include "arch/mips64/registers_mips64.h"
27#include "arch/x86/instruction_set_features_x86.h"
28#include "arch/x86/registers_x86.h"
29#include "arch/x86_64/instruction_set_features_x86_64.h"
30#include "base/macros.h"
31#include "builder.h"
32#include "code_generator_arm.h"
33#include "code_generator_arm64.h"
34#include "code_generator_mips.h"
35#include "code_generator_mips64.h"
36#include "code_generator_x86.h"
37#include "code_generator_x86_64.h"
38#include "code_simulator_container.h"
39#include "common_compiler_test.h"
40#include "dex_file.h"
41#include "dex_instruction.h"
42#include "driver/compiler_options.h"
43#include "graph_checker.h"
44#include "nodes.h"
45#include "optimizing_unit_test.h"
46#include "prepare_for_register_allocation.h"
47#include "register_allocator.h"
48#include "ssa_liveness_analysis.h"
49#include "utils.h"
50#include "utils/arm/managed_register_arm.h"
51#include "utils/mips/managed_register_mips.h"
52#include "utils/mips64/managed_register_mips64.h"
53#include "utils/x86/managed_register_x86.h"
54
55#include "gtest/gtest.h"
56
57namespace art {
58
59// Provide our own codegen, that ensures the C calling conventions
60// are preserved. Currently, ART and C do not match as R4 is caller-save
61// in ART, and callee-save in C. Alternatively, we could use or write
62// the stub that saves and restores all registers, but it is easier
63// to just overwrite the code generator.
64class TestCodeGeneratorARM : public arm::CodeGeneratorARM {
65 public:
66  TestCodeGeneratorARM(HGraph* graph,
67                       const ArmInstructionSetFeatures& isa_features,
68                       const CompilerOptions& compiler_options)
69      : arm::CodeGeneratorARM(graph, isa_features, compiler_options) {
70    AddAllocatedRegister(Location::RegisterLocation(arm::R6));
71    AddAllocatedRegister(Location::RegisterLocation(arm::R7));
72  }
73
74  void SetupBlockedRegisters() const OVERRIDE {
75    arm::CodeGeneratorARM::SetupBlockedRegisters();
76    blocked_core_registers_[arm::R4] = true;
77    blocked_core_registers_[arm::R6] = false;
78    blocked_core_registers_[arm::R7] = false;
79    // Makes pair R6-R7 available.
80    blocked_register_pairs_[arm::R6_R7] = false;
81  }
82};
83
84class TestCodeGeneratorX86 : public x86::CodeGeneratorX86 {
85 public:
86  TestCodeGeneratorX86(HGraph* graph,
87                       const X86InstructionSetFeatures& isa_features,
88                       const CompilerOptions& compiler_options)
89      : x86::CodeGeneratorX86(graph, isa_features, compiler_options) {
90    // Save edi, we need it for getting enough registers for long multiplication.
91    AddAllocatedRegister(Location::RegisterLocation(x86::EDI));
92  }
93
94  void SetupBlockedRegisters() const OVERRIDE {
95    x86::CodeGeneratorX86::SetupBlockedRegisters();
96    // ebx is a callee-save register in C, but caller-save for ART.
97    blocked_core_registers_[x86::EBX] = true;
98    blocked_register_pairs_[x86::EAX_EBX] = true;
99    blocked_register_pairs_[x86::EDX_EBX] = true;
100    blocked_register_pairs_[x86::ECX_EBX] = true;
101    blocked_register_pairs_[x86::EBX_EDI] = true;
102
103    // Make edi available.
104    blocked_core_registers_[x86::EDI] = false;
105    blocked_register_pairs_[x86::ECX_EDI] = false;
106  }
107};
108
109class InternalCodeAllocator : public CodeAllocator {
110 public:
111  InternalCodeAllocator() : size_(0) { }
112
113  virtual uint8_t* Allocate(size_t size) {
114    size_ = size;
115    memory_.reset(new uint8_t[size]);
116    return memory_.get();
117  }
118
119  size_t GetSize() const { return size_; }
120  uint8_t* GetMemory() const { return memory_.get(); }
121
122 private:
123  size_t size_;
124  std::unique_ptr<uint8_t[]> memory_;
125
126  DISALLOW_COPY_AND_ASSIGN(InternalCodeAllocator);
127};
128
129static bool CanExecuteOnHardware(InstructionSet target_isa) {
130  return (target_isa == kRuntimeISA)
131      // Handle the special case of ARM, with two instructions sets (ARM32 and Thumb-2).
132      || (kRuntimeISA == kArm && target_isa == kThumb2);
133}
134
135static bool CanExecute(InstructionSet target_isa) {
136  CodeSimulatorContainer simulator(target_isa);
137  return CanExecuteOnHardware(target_isa) || simulator.CanSimulate();
138}
139
140template <typename Expected>
141static Expected SimulatorExecute(CodeSimulator* simulator, Expected (*f)());
142
143template <>
144bool SimulatorExecute<bool>(CodeSimulator* simulator, bool (*f)()) {
145  simulator->RunFrom(reinterpret_cast<intptr_t>(f));
146  return simulator->GetCReturnBool();
147}
148
149template <>
150int32_t SimulatorExecute<int32_t>(CodeSimulator* simulator, int32_t (*f)()) {
151  simulator->RunFrom(reinterpret_cast<intptr_t>(f));
152  return simulator->GetCReturnInt32();
153}
154
155template <>
156int64_t SimulatorExecute<int64_t>(CodeSimulator* simulator, int64_t (*f)()) {
157  simulator->RunFrom(reinterpret_cast<intptr_t>(f));
158  return simulator->GetCReturnInt64();
159}
160
161template <typename Expected>
162static void VerifyGeneratedCode(InstructionSet target_isa,
163                                Expected (*f)(),
164                                bool has_result,
165                                Expected expected) {
166  ASSERT_TRUE(CanExecute(target_isa)) << "Target isa is not executable.";
167
168  // Verify on simulator.
169  CodeSimulatorContainer simulator(target_isa);
170  if (simulator.CanSimulate()) {
171    Expected result = SimulatorExecute<Expected>(simulator.Get(), f);
172    if (has_result) {
173      ASSERT_EQ(expected, result);
174    }
175  }
176
177  // Verify on hardware.
178  if (CanExecuteOnHardware(target_isa)) {
179    Expected result = f();
180    if (has_result) {
181      ASSERT_EQ(expected, result);
182    }
183  }
184}
185
186template <typename Expected>
187static void Run(const InternalCodeAllocator& allocator,
188                const CodeGenerator& codegen,
189                bool has_result,
190                Expected expected) {
191  InstructionSet target_isa = codegen.GetInstructionSet();
192
193  typedef Expected (*fptr)();
194  CommonCompilerTest::MakeExecutable(allocator.GetMemory(), allocator.GetSize());
195  fptr f = reinterpret_cast<fptr>(allocator.GetMemory());
196  if (target_isa == kThumb2) {
197    // For thumb we need the bottom bit set.
198    f = reinterpret_cast<fptr>(reinterpret_cast<uintptr_t>(f) + 1);
199  }
200  VerifyGeneratedCode(target_isa, f, has_result, expected);
201}
202
203template <typename Expected>
204static void RunCode(CodeGenerator* codegen,
205                    HGraph* graph,
206                    std::function<void(HGraph*)> hook_before_codegen,
207                    bool has_result,
208                    Expected expected) {
209  ASSERT_TRUE(graph->IsInSsaForm());
210
211  SSAChecker graph_checker(graph);
212  graph_checker.Run();
213  ASSERT_TRUE(graph_checker.IsValid());
214
215  SsaLivenessAnalysis liveness(graph, codegen);
216
217  PrepareForRegisterAllocation(graph).Run();
218  liveness.Analyze();
219  RegisterAllocator(graph->GetArena(), codegen, liveness).AllocateRegisters();
220  hook_before_codegen(graph);
221
222  InternalCodeAllocator allocator;
223  codegen->Compile(&allocator);
224  Run(allocator, *codegen, has_result, expected);
225}
226
227template <typename Expected>
228static void RunCode(InstructionSet target_isa,
229                    HGraph* graph,
230                    std::function<void(HGraph*)> hook_before_codegen,
231                    bool has_result,
232                    Expected expected) {
233  CompilerOptions compiler_options;
234  if (target_isa == kArm || target_isa == kThumb2) {
235    std::unique_ptr<const ArmInstructionSetFeatures> features_arm(
236        ArmInstructionSetFeatures::FromCppDefines());
237    TestCodeGeneratorARM codegenARM(graph, *features_arm.get(), compiler_options);
238    RunCode(&codegenARM, graph, hook_before_codegen, has_result, expected);
239  } else if (target_isa == kArm64) {
240    std::unique_ptr<const Arm64InstructionSetFeatures> features_arm64(
241        Arm64InstructionSetFeatures::FromCppDefines());
242    arm64::CodeGeneratorARM64 codegenARM64(graph, *features_arm64.get(), compiler_options);
243    RunCode(&codegenARM64, graph, hook_before_codegen, has_result, expected);
244  } else if (target_isa == kX86) {
245    std::unique_ptr<const X86InstructionSetFeatures> features_x86(
246        X86InstructionSetFeatures::FromCppDefines());
247    x86::CodeGeneratorX86 codegenX86(graph, *features_x86.get(), compiler_options);
248    RunCode(&codegenX86, graph, hook_before_codegen, has_result, expected);
249  } else if (target_isa == kX86_64) {
250    std::unique_ptr<const X86_64InstructionSetFeatures> features_x86_64(
251        X86_64InstructionSetFeatures::FromCppDefines());
252    x86_64::CodeGeneratorX86_64 codegenX86_64(graph, *features_x86_64.get(), compiler_options);
253    RunCode(&codegenX86_64, graph, hook_before_codegen, has_result, expected);
254  } else if (target_isa == kMips) {
255    std::unique_ptr<const MipsInstructionSetFeatures> features_mips(
256        MipsInstructionSetFeatures::FromCppDefines());
257    mips::CodeGeneratorMIPS codegenMIPS(graph, *features_mips.get(), compiler_options);
258    RunCode(&codegenMIPS, graph, hook_before_codegen, has_result, expected);
259  } else if (target_isa == kMips64) {
260    std::unique_ptr<const Mips64InstructionSetFeatures> features_mips64(
261        Mips64InstructionSetFeatures::FromCppDefines());
262    mips64::CodeGeneratorMIPS64 codegenMIPS64(graph, *features_mips64.get(), compiler_options);
263    RunCode(&codegenMIPS64, graph, hook_before_codegen, has_result, expected);
264  }
265}
266
267static ::std::vector<InstructionSet> GetTargetISAs() {
268  ::std::vector<InstructionSet> v;
269  // Add all ISAs that are executable on hardware or on simulator.
270  const ::std::vector<InstructionSet> executable_isa_candidates = {
271    kArm,
272    kArm64,
273    kThumb2,
274    kX86,
275    kX86_64,
276    kMips,
277    kMips64
278  };
279
280  for (auto target_isa : executable_isa_candidates) {
281    if (CanExecute(target_isa)) {
282      v.push_back(target_isa);
283    }
284  }
285
286  return v;
287}
288
289static void TestCode(const uint16_t* data,
290                     bool has_result = false,
291                     int32_t expected = 0) {
292  for (InstructionSet target_isa : GetTargetISAs()) {
293    ArenaPool pool;
294    ArenaAllocator arena(&pool);
295    HGraph* graph = CreateGraph(&arena);
296    HGraphBuilder builder(graph);
297    const DexFile::CodeItem* item = reinterpret_cast<const DexFile::CodeItem*>(data);
298    bool graph_built = builder.BuildGraph(*item);
299    ASSERT_TRUE(graph_built);
300    // Remove suspend checks, they cannot be executed in this context.
301    RemoveSuspendChecks(graph);
302    TransformToSsa(graph);
303    RunCode(target_isa, graph, [](HGraph*) {}, has_result, expected);
304  }
305}
306
307static void TestCodeLong(const uint16_t* data,
308                         bool has_result,
309                         int64_t expected) {
310  for (InstructionSet target_isa : GetTargetISAs()) {
311    ArenaPool pool;
312    ArenaAllocator arena(&pool);
313    HGraph* graph = CreateGraph(&arena);
314    HGraphBuilder builder(graph, Primitive::kPrimLong);
315    const DexFile::CodeItem* item = reinterpret_cast<const DexFile::CodeItem*>(data);
316    bool graph_built = builder.BuildGraph(*item);
317    ASSERT_TRUE(graph_built);
318    // Remove suspend checks, they cannot be executed in this context.
319    RemoveSuspendChecks(graph);
320    TransformToSsa(graph);
321    RunCode(target_isa, graph, [](HGraph*) {}, has_result, expected);
322  }
323}
324
325class CodegenTest : public CommonCompilerTest {};
326
327TEST_F(CodegenTest, ReturnVoid) {
328  const uint16_t data[] = ZERO_REGISTER_CODE_ITEM(Instruction::RETURN_VOID);
329  TestCode(data);
330}
331
332TEST_F(CodegenTest, CFG1) {
333  const uint16_t data[] = ZERO_REGISTER_CODE_ITEM(
334    Instruction::GOTO | 0x100,
335    Instruction::RETURN_VOID);
336
337  TestCode(data);
338}
339
340TEST_F(CodegenTest, CFG2) {
341  const uint16_t data[] = ZERO_REGISTER_CODE_ITEM(
342    Instruction::GOTO | 0x100,
343    Instruction::GOTO | 0x100,
344    Instruction::RETURN_VOID);
345
346  TestCode(data);
347}
348
349TEST_F(CodegenTest, CFG3) {
350  const uint16_t data1[] = ZERO_REGISTER_CODE_ITEM(
351    Instruction::GOTO | 0x200,
352    Instruction::RETURN_VOID,
353    Instruction::GOTO | 0xFF00);
354
355  TestCode(data1);
356
357  const uint16_t data2[] = ZERO_REGISTER_CODE_ITEM(
358    Instruction::GOTO_16, 3,
359    Instruction::RETURN_VOID,
360    Instruction::GOTO_16, 0xFFFF);
361
362  TestCode(data2);
363
364  const uint16_t data3[] = ZERO_REGISTER_CODE_ITEM(
365    Instruction::GOTO_32, 4, 0,
366    Instruction::RETURN_VOID,
367    Instruction::GOTO_32, 0xFFFF, 0xFFFF);
368
369  TestCode(data3);
370}
371
372TEST_F(CodegenTest, CFG4) {
373  const uint16_t data[] = ZERO_REGISTER_CODE_ITEM(
374    Instruction::RETURN_VOID,
375    Instruction::GOTO | 0x100,
376    Instruction::GOTO | 0xFE00);
377
378  TestCode(data);
379}
380
381TEST_F(CodegenTest, CFG5) {
382  const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
383    Instruction::CONST_4 | 0 | 0,
384    Instruction::IF_EQ, 3,
385    Instruction::GOTO | 0x100,
386    Instruction::RETURN_VOID);
387
388  TestCode(data);
389}
390
391TEST_F(CodegenTest, IntConstant) {
392  const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
393    Instruction::CONST_4 | 0 | 0,
394    Instruction::RETURN_VOID);
395
396  TestCode(data);
397}
398
399TEST_F(CodegenTest, Return1) {
400  const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
401    Instruction::CONST_4 | 0 | 0,
402    Instruction::RETURN | 0);
403
404  TestCode(data, true, 0);
405}
406
407TEST_F(CodegenTest, Return2) {
408  const uint16_t data[] = TWO_REGISTERS_CODE_ITEM(
409    Instruction::CONST_4 | 0 | 0,
410    Instruction::CONST_4 | 0 | 1 << 8,
411    Instruction::RETURN | 1 << 8);
412
413  TestCode(data, true, 0);
414}
415
416TEST_F(CodegenTest, Return3) {
417  const uint16_t data[] = TWO_REGISTERS_CODE_ITEM(
418    Instruction::CONST_4 | 0 | 0,
419    Instruction::CONST_4 | 1 << 8 | 1 << 12,
420    Instruction::RETURN | 1 << 8);
421
422  TestCode(data, true, 1);
423}
424
425TEST_F(CodegenTest, ReturnIf1) {
426  const uint16_t data[] = TWO_REGISTERS_CODE_ITEM(
427    Instruction::CONST_4 | 0 | 0,
428    Instruction::CONST_4 | 1 << 8 | 1 << 12,
429    Instruction::IF_EQ, 3,
430    Instruction::RETURN | 0 << 8,
431    Instruction::RETURN | 1 << 8);
432
433  TestCode(data, true, 1);
434}
435
436TEST_F(CodegenTest, ReturnIf2) {
437  const uint16_t data[] = TWO_REGISTERS_CODE_ITEM(
438    Instruction::CONST_4 | 0 | 0,
439    Instruction::CONST_4 | 1 << 8 | 1 << 12,
440    Instruction::IF_EQ | 0 << 4 | 1 << 8, 3,
441    Instruction::RETURN | 0 << 8,
442    Instruction::RETURN | 1 << 8);
443
444  TestCode(data, true, 0);
445}
446
447// Exercise bit-wise (one's complement) not-int instruction.
448#define NOT_INT_TEST(TEST_NAME, INPUT, EXPECTED_OUTPUT) \
449TEST_F(CodegenTest, TEST_NAME) {                        \
450  const int32_t input = INPUT;                          \
451  const uint16_t input_lo = Low16Bits(input);           \
452  const uint16_t input_hi = High16Bits(input);          \
453  const uint16_t data[] = TWO_REGISTERS_CODE_ITEM(      \
454      Instruction::CONST | 0 << 8, input_lo, input_hi,  \
455      Instruction::NOT_INT | 1 << 8 | 0 << 12 ,         \
456      Instruction::RETURN | 1 << 8);                    \
457                                                        \
458  TestCode(data, true, EXPECTED_OUTPUT);                \
459}
460
461NOT_INT_TEST(ReturnNotIntMinus2, -2, 1)
462NOT_INT_TEST(ReturnNotIntMinus1, -1, 0)
463NOT_INT_TEST(ReturnNotInt0, 0, -1)
464NOT_INT_TEST(ReturnNotInt1, 1, -2)
465NOT_INT_TEST(ReturnNotIntINT32_MIN, -2147483648, 2147483647)  // (2^31) - 1
466NOT_INT_TEST(ReturnNotIntINT32_MINPlus1, -2147483647, 2147483646)  // (2^31) - 2
467NOT_INT_TEST(ReturnNotIntINT32_MAXMinus1, 2147483646, -2147483647)  // -(2^31) - 1
468NOT_INT_TEST(ReturnNotIntINT32_MAX, 2147483647, -2147483648)  // -(2^31)
469
470#undef NOT_INT_TEST
471
472// Exercise bit-wise (one's complement) not-long instruction.
473#define NOT_LONG_TEST(TEST_NAME, INPUT, EXPECTED_OUTPUT)                 \
474TEST_F(CodegenTest, TEST_NAME) {                                         \
475  const int64_t input = INPUT;                                           \
476  const uint16_t word0 = Low16Bits(Low32Bits(input));   /* LSW. */       \
477  const uint16_t word1 = High16Bits(Low32Bits(input));                   \
478  const uint16_t word2 = Low16Bits(High32Bits(input));                   \
479  const uint16_t word3 = High16Bits(High32Bits(input)); /* MSW. */       \
480  const uint16_t data[] = FOUR_REGISTERS_CODE_ITEM(                      \
481      Instruction::CONST_WIDE | 0 << 8, word0, word1, word2, word3,      \
482      Instruction::NOT_LONG | 2 << 8 | 0 << 12,                          \
483      Instruction::RETURN_WIDE | 2 << 8);                                \
484                                                                         \
485  TestCodeLong(data, true, EXPECTED_OUTPUT);                             \
486}
487
488NOT_LONG_TEST(ReturnNotLongMinus2, INT64_C(-2), INT64_C(1))
489NOT_LONG_TEST(ReturnNotLongMinus1, INT64_C(-1), INT64_C(0))
490NOT_LONG_TEST(ReturnNotLong0, INT64_C(0), INT64_C(-1))
491NOT_LONG_TEST(ReturnNotLong1, INT64_C(1), INT64_C(-2))
492
493NOT_LONG_TEST(ReturnNotLongINT32_MIN,
494              INT64_C(-2147483648),
495              INT64_C(2147483647))  // (2^31) - 1
496NOT_LONG_TEST(ReturnNotLongINT32_MINPlus1,
497              INT64_C(-2147483647),
498              INT64_C(2147483646))  // (2^31) - 2
499NOT_LONG_TEST(ReturnNotLongINT32_MAXMinus1,
500              INT64_C(2147483646),
501              INT64_C(-2147483647))  // -(2^31) - 1
502NOT_LONG_TEST(ReturnNotLongINT32_MAX,
503              INT64_C(2147483647),
504              INT64_C(-2147483648))  // -(2^31)
505
506// Note that the C++ compiler won't accept
507// INT64_C(-9223372036854775808) (that is, INT64_MIN) as a valid
508// int64_t literal, so we use INT64_C(-9223372036854775807)-1 instead.
509NOT_LONG_TEST(ReturnNotINT64_MIN,
510              INT64_C(-9223372036854775807)-1,
511              INT64_C(9223372036854775807));  // (2^63) - 1
512NOT_LONG_TEST(ReturnNotINT64_MINPlus1,
513              INT64_C(-9223372036854775807),
514              INT64_C(9223372036854775806));  // (2^63) - 2
515NOT_LONG_TEST(ReturnNotLongINT64_MAXMinus1,
516              INT64_C(9223372036854775806),
517              INT64_C(-9223372036854775807));  // -(2^63) - 1
518NOT_LONG_TEST(ReturnNotLongINT64_MAX,
519              INT64_C(9223372036854775807),
520              INT64_C(-9223372036854775807)-1);  // -(2^63)
521
522#undef NOT_LONG_TEST
523
524TEST_F(CodegenTest, IntToLongOfLongToInt) {
525  const int64_t input = INT64_C(4294967296);             // 2^32
526  const uint16_t word0 = Low16Bits(Low32Bits(input));    // LSW.
527  const uint16_t word1 = High16Bits(Low32Bits(input));
528  const uint16_t word2 = Low16Bits(High32Bits(input));
529  const uint16_t word3 = High16Bits(High32Bits(input));  // MSW.
530  const uint16_t data[] = FIVE_REGISTERS_CODE_ITEM(
531      Instruction::CONST_WIDE | 0 << 8, word0, word1, word2, word3,
532      Instruction::CONST_WIDE | 2 << 8, 1, 0, 0, 0,
533      Instruction::ADD_LONG | 0, 0 << 8 | 2,             // v0 <- 2^32 + 1
534      Instruction::LONG_TO_INT | 4 << 8 | 0 << 12,
535      Instruction::INT_TO_LONG | 2 << 8 | 4 << 12,
536      Instruction::RETURN_WIDE | 2 << 8);
537
538  TestCodeLong(data, true, 1);
539}
540
541TEST_F(CodegenTest, ReturnAdd1) {
542  const uint16_t data[] = TWO_REGISTERS_CODE_ITEM(
543    Instruction::CONST_4 | 3 << 12 | 0,
544    Instruction::CONST_4 | 4 << 12 | 1 << 8,
545    Instruction::ADD_INT, 1 << 8 | 0,
546    Instruction::RETURN);
547
548  TestCode(data, true, 7);
549}
550
551TEST_F(CodegenTest, ReturnAdd2) {
552  const uint16_t data[] = TWO_REGISTERS_CODE_ITEM(
553    Instruction::CONST_4 | 3 << 12 | 0,
554    Instruction::CONST_4 | 4 << 12 | 1 << 8,
555    Instruction::ADD_INT_2ADDR | 1 << 12,
556    Instruction::RETURN);
557
558  TestCode(data, true, 7);
559}
560
561TEST_F(CodegenTest, ReturnAdd3) {
562  const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
563    Instruction::CONST_4 | 4 << 12 | 0 << 8,
564    Instruction::ADD_INT_LIT8, 3 << 8 | 0,
565    Instruction::RETURN);
566
567  TestCode(data, true, 7);
568}
569
570TEST_F(CodegenTest, ReturnAdd4) {
571  const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
572    Instruction::CONST_4 | 4 << 12 | 0 << 8,
573    Instruction::ADD_INT_LIT16, 3,
574    Instruction::RETURN);
575
576  TestCode(data, true, 7);
577}
578
579TEST_F(CodegenTest, ReturnMulInt) {
580  const uint16_t data[] = TWO_REGISTERS_CODE_ITEM(
581    Instruction::CONST_4 | 3 << 12 | 0,
582    Instruction::CONST_4 | 4 << 12 | 1 << 8,
583    Instruction::MUL_INT, 1 << 8 | 0,
584    Instruction::RETURN);
585
586  TestCode(data, true, 12);
587}
588
589TEST_F(CodegenTest, ReturnMulInt2addr) {
590  const uint16_t data[] = TWO_REGISTERS_CODE_ITEM(
591    Instruction::CONST_4 | 3 << 12 | 0,
592    Instruction::CONST_4 | 4 << 12 | 1 << 8,
593    Instruction::MUL_INT_2ADDR | 1 << 12,
594    Instruction::RETURN);
595
596  TestCode(data, true, 12);
597}
598
599TEST_F(CodegenTest, ReturnMulLong) {
600  const uint16_t data[] = FOUR_REGISTERS_CODE_ITEM(
601    Instruction::CONST_WIDE | 0 << 8, 3, 0, 0, 0,
602    Instruction::CONST_WIDE | 2 << 8, 4, 0, 0, 0,
603    Instruction::MUL_LONG, 2 << 8 | 0,
604    Instruction::RETURN_WIDE);
605
606  TestCodeLong(data, true, 12);
607}
608
609TEST_F(CodegenTest, ReturnMulLong2addr) {
610  const uint16_t data[] = FOUR_REGISTERS_CODE_ITEM(
611    Instruction::CONST_WIDE | 0 << 8, 3, 0, 0, 0,
612    Instruction::CONST_WIDE | 2 << 8, 4, 0, 0, 0,
613    Instruction::MUL_LONG_2ADDR | 2 << 12,
614    Instruction::RETURN_WIDE);
615
616  TestCodeLong(data, true, 12);
617}
618
619TEST_F(CodegenTest, ReturnMulIntLit8) {
620  const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
621    Instruction::CONST_4 | 4 << 12 | 0 << 8,
622    Instruction::MUL_INT_LIT8, 3 << 8 | 0,
623    Instruction::RETURN);
624
625  TestCode(data, true, 12);
626}
627
628TEST_F(CodegenTest, ReturnMulIntLit16) {
629  const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
630    Instruction::CONST_4 | 4 << 12 | 0 << 8,
631    Instruction::MUL_INT_LIT16, 3,
632    Instruction::RETURN);
633
634  TestCode(data, true, 12);
635}
636
637TEST_F(CodegenTest, NonMaterializedCondition) {
638  for (InstructionSet target_isa : GetTargetISAs()) {
639    ArenaPool pool;
640    ArenaAllocator allocator(&pool);
641
642    HGraph* graph = CreateGraph(&allocator);
643    HBasicBlock* entry = new (&allocator) HBasicBlock(graph);
644    graph->AddBlock(entry);
645    graph->SetEntryBlock(entry);
646    entry->AddInstruction(new (&allocator) HGoto());
647
648    HBasicBlock* first_block = new (&allocator) HBasicBlock(graph);
649    graph->AddBlock(first_block);
650    entry->AddSuccessor(first_block);
651    HIntConstant* constant0 = graph->GetIntConstant(0);
652    HIntConstant* constant1 = graph->GetIntConstant(1);
653    HEqual* equal = new (&allocator) HEqual(constant0, constant0);
654    first_block->AddInstruction(equal);
655    first_block->AddInstruction(new (&allocator) HIf(equal));
656
657    HBasicBlock* then_block = new (&allocator) HBasicBlock(graph);
658    HBasicBlock* else_block = new (&allocator) HBasicBlock(graph);
659    HBasicBlock* exit_block = new (&allocator) HBasicBlock(graph);
660    graph->SetExitBlock(exit_block);
661
662    graph->AddBlock(then_block);
663    graph->AddBlock(else_block);
664    graph->AddBlock(exit_block);
665    first_block->AddSuccessor(then_block);
666    first_block->AddSuccessor(else_block);
667    then_block->AddSuccessor(exit_block);
668    else_block->AddSuccessor(exit_block);
669
670    exit_block->AddInstruction(new (&allocator) HExit());
671    then_block->AddInstruction(new (&allocator) HReturn(constant0));
672    else_block->AddInstruction(new (&allocator) HReturn(constant1));
673
674    ASSERT_FALSE(equal->IsEmittedAtUseSite());
675    TransformToSsa(graph);
676    PrepareForRegisterAllocation(graph).Run();
677    ASSERT_TRUE(equal->IsEmittedAtUseSite());
678
679    auto hook_before_codegen = [](HGraph* graph_in) {
680      HBasicBlock* block = graph_in->GetEntryBlock()->GetSuccessors()[0];
681      HParallelMove* move = new (graph_in->GetArena()) HParallelMove(graph_in->GetArena());
682      block->InsertInstructionBefore(move, block->GetLastInstruction());
683    };
684
685    RunCode(target_isa, graph, hook_before_codegen, true, 0);
686  }
687}
688
689TEST_F(CodegenTest, MaterializedCondition1) {
690  for (InstructionSet target_isa : GetTargetISAs()) {
691    // Check that condition are materialized correctly. A materialized condition
692    // should yield `1` if it evaluated to true, and `0` otherwise.
693    // We force the materialization of comparisons for different combinations of
694
695    // inputs and check the results.
696
697    int lhs[] = {1, 2, -1, 2, 0xabc};
698    int rhs[] = {2, 1, 2, -1, 0xabc};
699
700    for (size_t i = 0; i < arraysize(lhs); i++) {
701      ArenaPool pool;
702      ArenaAllocator allocator(&pool);
703      HGraph* graph = CreateGraph(&allocator);
704
705      HBasicBlock* entry_block = new (&allocator) HBasicBlock(graph);
706      graph->AddBlock(entry_block);
707      graph->SetEntryBlock(entry_block);
708      entry_block->AddInstruction(new (&allocator) HGoto());
709      HBasicBlock* code_block = new (&allocator) HBasicBlock(graph);
710      graph->AddBlock(code_block);
711      HBasicBlock* exit_block = new (&allocator) HBasicBlock(graph);
712      graph->AddBlock(exit_block);
713      exit_block->AddInstruction(new (&allocator) HExit());
714
715      entry_block->AddSuccessor(code_block);
716      code_block->AddSuccessor(exit_block);
717      graph->SetExitBlock(exit_block);
718
719      HIntConstant* cst_lhs = graph->GetIntConstant(lhs[i]);
720      HIntConstant* cst_rhs = graph->GetIntConstant(rhs[i]);
721      HLessThan cmp_lt(cst_lhs, cst_rhs);
722      code_block->AddInstruction(&cmp_lt);
723      HReturn ret(&cmp_lt);
724      code_block->AddInstruction(&ret);
725
726      TransformToSsa(graph);
727      auto hook_before_codegen = [](HGraph* graph_in) {
728        HBasicBlock* block = graph_in->GetEntryBlock()->GetSuccessors()[0];
729        HParallelMove* move = new (graph_in->GetArena()) HParallelMove(graph_in->GetArena());
730        block->InsertInstructionBefore(move, block->GetLastInstruction());
731      };
732      RunCode(target_isa, graph, hook_before_codegen, true, lhs[i] < rhs[i]);
733    }
734  }
735}
736
737TEST_F(CodegenTest, MaterializedCondition2) {
738  for (InstructionSet target_isa : GetTargetISAs()) {
739    // Check that HIf correctly interprets a materialized condition.
740    // We force the materialization of comparisons for different combinations of
741    // inputs. An HIf takes the materialized combination as input and returns a
742    // value that we verify.
743
744    int lhs[] = {1, 2, -1, 2, 0xabc};
745    int rhs[] = {2, 1, 2, -1, 0xabc};
746
747
748    for (size_t i = 0; i < arraysize(lhs); i++) {
749      ArenaPool pool;
750      ArenaAllocator allocator(&pool);
751      HGraph* graph = CreateGraph(&allocator);
752
753      HBasicBlock* entry_block = new (&allocator) HBasicBlock(graph);
754      graph->AddBlock(entry_block);
755      graph->SetEntryBlock(entry_block);
756      entry_block->AddInstruction(new (&allocator) HGoto());
757
758      HBasicBlock* if_block = new (&allocator) HBasicBlock(graph);
759      graph->AddBlock(if_block);
760      HBasicBlock* if_true_block = new (&allocator) HBasicBlock(graph);
761      graph->AddBlock(if_true_block);
762      HBasicBlock* if_false_block = new (&allocator) HBasicBlock(graph);
763      graph->AddBlock(if_false_block);
764      HBasicBlock* exit_block = new (&allocator) HBasicBlock(graph);
765      graph->AddBlock(exit_block);
766      exit_block->AddInstruction(new (&allocator) HExit());
767
768      graph->SetEntryBlock(entry_block);
769      entry_block->AddSuccessor(if_block);
770      if_block->AddSuccessor(if_true_block);
771      if_block->AddSuccessor(if_false_block);
772      if_true_block->AddSuccessor(exit_block);
773      if_false_block->AddSuccessor(exit_block);
774      graph->SetExitBlock(exit_block);
775
776      HIntConstant* cst_lhs = graph->GetIntConstant(lhs[i]);
777      HIntConstant* cst_rhs = graph->GetIntConstant(rhs[i]);
778      HLessThan cmp_lt(cst_lhs, cst_rhs);
779      if_block->AddInstruction(&cmp_lt);
780      // We insert a dummy instruction to separate the HIf from the HLessThan
781      // and force the materialization of the condition.
782      HMemoryBarrier force_materialization(MemBarrierKind::kAnyAny, 0);
783      if_block->AddInstruction(&force_materialization);
784      HIf if_lt(&cmp_lt);
785      if_block->AddInstruction(&if_lt);
786
787      HIntConstant* cst_lt = graph->GetIntConstant(1);
788      HReturn ret_lt(cst_lt);
789      if_true_block->AddInstruction(&ret_lt);
790      HIntConstant* cst_ge = graph->GetIntConstant(0);
791      HReturn ret_ge(cst_ge);
792      if_false_block->AddInstruction(&ret_ge);
793
794      TransformToSsa(graph);
795      auto hook_before_codegen = [](HGraph* graph_in) {
796        HBasicBlock* block = graph_in->GetEntryBlock()->GetSuccessors()[0];
797        HParallelMove* move = new (graph_in->GetArena()) HParallelMove(graph_in->GetArena());
798        block->InsertInstructionBefore(move, block->GetLastInstruction());
799      };
800      RunCode(target_isa, graph, hook_before_codegen, true, lhs[i] < rhs[i]);
801    }
802  }
803}
804
805TEST_F(CodegenTest, ReturnDivIntLit8) {
806  const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
807    Instruction::CONST_4 | 4 << 12 | 0 << 8,
808    Instruction::DIV_INT_LIT8, 3 << 8 | 0,
809    Instruction::RETURN);
810
811  TestCode(data, true, 1);
812}
813
814TEST_F(CodegenTest, ReturnDivInt2Addr) {
815  const uint16_t data[] = TWO_REGISTERS_CODE_ITEM(
816    Instruction::CONST_4 | 4 << 12 | 0,
817    Instruction::CONST_4 | 2 << 12 | 1 << 8,
818    Instruction::DIV_INT_2ADDR | 1 << 12,
819    Instruction::RETURN);
820
821  TestCode(data, true, 2);
822}
823
824// Helper method.
825static void TestComparison(IfCondition condition,
826                           int64_t i,
827                           int64_t j,
828                           Primitive::Type type,
829                           const InstructionSet target_isa) {
830  ArenaPool pool;
831  ArenaAllocator allocator(&pool);
832  HGraph* graph = CreateGraph(&allocator);
833
834  HBasicBlock* entry_block = new (&allocator) HBasicBlock(graph);
835  graph->AddBlock(entry_block);
836  graph->SetEntryBlock(entry_block);
837  entry_block->AddInstruction(new (&allocator) HGoto());
838
839  HBasicBlock* block = new (&allocator) HBasicBlock(graph);
840  graph->AddBlock(block);
841
842  HBasicBlock* exit_block = new (&allocator) HBasicBlock(graph);
843  graph->AddBlock(exit_block);
844  graph->SetExitBlock(exit_block);
845  exit_block->AddInstruction(new (&allocator) HExit());
846
847  entry_block->AddSuccessor(block);
848  block->AddSuccessor(exit_block);
849
850  HInstruction* op1;
851  HInstruction* op2;
852  if (type == Primitive::kPrimInt) {
853    op1 = graph->GetIntConstant(i);
854    op2 = graph->GetIntConstant(j);
855  } else {
856    DCHECK_EQ(type, Primitive::kPrimLong);
857    op1 = graph->GetLongConstant(i);
858    op2 = graph->GetLongConstant(j);
859  }
860
861  HInstruction* comparison = nullptr;
862  bool expected_result = false;
863  const uint64_t x = i;
864  const uint64_t y = j;
865  switch (condition) {
866    case kCondEQ:
867      comparison = new (&allocator) HEqual(op1, op2);
868      expected_result = (i == j);
869      break;
870    case kCondNE:
871      comparison = new (&allocator) HNotEqual(op1, op2);
872      expected_result = (i != j);
873      break;
874    case kCondLT:
875      comparison = new (&allocator) HLessThan(op1, op2);
876      expected_result = (i < j);
877      break;
878    case kCondLE:
879      comparison = new (&allocator) HLessThanOrEqual(op1, op2);
880      expected_result = (i <= j);
881      break;
882    case kCondGT:
883      comparison = new (&allocator) HGreaterThan(op1, op2);
884      expected_result = (i > j);
885      break;
886    case kCondGE:
887      comparison = new (&allocator) HGreaterThanOrEqual(op1, op2);
888      expected_result = (i >= j);
889      break;
890    case kCondB:
891      comparison = new (&allocator) HBelow(op1, op2);
892      expected_result = (x < y);
893      break;
894    case kCondBE:
895      comparison = new (&allocator) HBelowOrEqual(op1, op2);
896      expected_result = (x <= y);
897      break;
898    case kCondA:
899      comparison = new (&allocator) HAbove(op1, op2);
900      expected_result = (x > y);
901      break;
902    case kCondAE:
903      comparison = new (&allocator) HAboveOrEqual(op1, op2);
904      expected_result = (x >= y);
905      break;
906  }
907  block->AddInstruction(comparison);
908  block->AddInstruction(new (&allocator) HReturn(comparison));
909
910  TransformToSsa(graph);
911  RunCode(target_isa, graph, [](HGraph*) {}, true, expected_result);
912}
913
914TEST_F(CodegenTest, ComparisonsInt) {
915  for (InstructionSet target_isa : GetTargetISAs()) {
916    for (int64_t i = -1; i <= 1; i++) {
917      for (int64_t j = -1; j <= 1; j++) {
918        TestComparison(kCondEQ, i, j, Primitive::kPrimInt, target_isa);
919        TestComparison(kCondNE, i, j, Primitive::kPrimInt, target_isa);
920        TestComparison(kCondLT, i, j, Primitive::kPrimInt, target_isa);
921        TestComparison(kCondLE, i, j, Primitive::kPrimInt, target_isa);
922        TestComparison(kCondGT, i, j, Primitive::kPrimInt, target_isa);
923        TestComparison(kCondGE, i, j, Primitive::kPrimInt, target_isa);
924        TestComparison(kCondB,  i, j, Primitive::kPrimInt, target_isa);
925        TestComparison(kCondBE, i, j, Primitive::kPrimInt, target_isa);
926        TestComparison(kCondA,  i, j, Primitive::kPrimInt, target_isa);
927        TestComparison(kCondAE, i, j, Primitive::kPrimInt, target_isa);
928      }
929    }
930  }
931}
932
933TEST_F(CodegenTest, ComparisonsLong) {
934  // TODO: make MIPS work for long
935  if (kRuntimeISA == kMips || kRuntimeISA == kMips64) {
936    return;
937  }
938
939  for (InstructionSet target_isa : GetTargetISAs()) {
940    if (target_isa == kMips || target_isa == kMips64) {
941      continue;
942    }
943
944    for (int64_t i = -1; i <= 1; i++) {
945      for (int64_t j = -1; j <= 1; j++) {
946        TestComparison(kCondEQ, i, j, Primitive::kPrimLong, target_isa);
947        TestComparison(kCondNE, i, j, Primitive::kPrimLong, target_isa);
948        TestComparison(kCondLT, i, j, Primitive::kPrimLong, target_isa);
949        TestComparison(kCondLE, i, j, Primitive::kPrimLong, target_isa);
950        TestComparison(kCondGT, i, j, Primitive::kPrimLong, target_isa);
951        TestComparison(kCondGE, i, j, Primitive::kPrimLong, target_isa);
952        TestComparison(kCondB,  i, j, Primitive::kPrimLong, target_isa);
953        TestComparison(kCondBE, i, j, Primitive::kPrimLong, target_isa);
954        TestComparison(kCondA,  i, j, Primitive::kPrimLong, target_isa);
955        TestComparison(kCondAE, i, j, Primitive::kPrimLong, target_isa);
956      }
957    }
958  }
959}
960
961}  // namespace art
962