]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp
Vendor import of lldb release_39 branch r276489:
[FreeBSD/FreeBSD.git] / source / Plugins / ABI / SysV-ppc / ABISysV_ppc.cpp
1 //===-- ABISysV_ppc.cpp -----------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "ABISysV_ppc.h"
11
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/Triple.h"
17
18 // Project includes
19 #include "lldb/Core/ConstString.h"
20 #include "lldb/Core/DataExtractor.h"
21 #include "lldb/Core/Error.h"
22 #include "lldb/Core/Log.h"
23 #include "lldb/Core/Module.h"
24 #include "lldb/Core/PluginManager.h"
25 #include "lldb/Core/RegisterValue.h"
26 #include "lldb/Core/Value.h"
27 #include "lldb/Core/ValueObjectConstResult.h"
28 #include "lldb/Core/ValueObjectRegister.h"
29 #include "lldb/Core/ValueObjectMemory.h"
30 #include "lldb/Symbol/UnwindPlan.h"
31 #include "lldb/Target/Target.h"
32 #include "lldb/Target/Process.h"
33 #include "lldb/Target/RegisterContext.h"
34 #include "lldb/Target/StackFrame.h"
35 #include "lldb/Target/Thread.h"
36
37 using namespace lldb;
38 using namespace lldb_private;
39
40 enum dwarf_regnums
41 {
42     dwarf_r0 = 0,
43     dwarf_r1,
44     dwarf_r2,
45     dwarf_r3,
46     dwarf_r4,
47     dwarf_r5,
48     dwarf_r6,
49     dwarf_r7,
50     dwarf_r8,
51     dwarf_r9,
52     dwarf_r10,
53     dwarf_r11,
54     dwarf_r12,
55     dwarf_r13,
56     dwarf_r14,
57     dwarf_r15,
58     dwarf_r16,
59     dwarf_r17,
60     dwarf_r18,
61     dwarf_r19,
62     dwarf_r20,
63     dwarf_r21,
64     dwarf_r22,
65     dwarf_r23,
66     dwarf_r24,
67     dwarf_r25,
68     dwarf_r26,
69     dwarf_r27,
70     dwarf_r28,
71     dwarf_r29,
72     dwarf_r30,
73     dwarf_r31,
74     dwarf_f0,
75     dwarf_f1,
76     dwarf_f2,
77     dwarf_f3,
78     dwarf_f4,
79     dwarf_f5,
80     dwarf_f6,
81     dwarf_f7,
82     dwarf_f8,
83     dwarf_f9,
84     dwarf_f10,
85     dwarf_f11,
86     dwarf_f12,
87     dwarf_f13,
88     dwarf_f14,
89     dwarf_f15,
90     dwarf_f16,
91     dwarf_f17,
92     dwarf_f18,
93     dwarf_f19,
94     dwarf_f20,
95     dwarf_f21,
96     dwarf_f22,
97     dwarf_f23,
98     dwarf_f24,
99     dwarf_f25,
100     dwarf_f26,
101     dwarf_f27,
102     dwarf_f28,
103     dwarf_f29,
104     dwarf_f30,
105     dwarf_f31,
106     dwarf_cr,
107     dwarf_fpscr,
108     dwarf_xer = 101,
109     dwarf_lr = 108,
110     dwarf_ctr,
111     dwarf_pc,
112     dwarf_cfa,
113 };
114
115 // Note that the size and offset will be updated by platform-specific classes.
116 #define DEFINE_GPR(reg, alt, kind1, kind2, kind3, kind4)           \
117     { #reg, alt, 8, 0, eEncodingUint, \
118       eFormatHex, { kind1, kind2, kind3, kind4}, nullptr, nullptr }
119
120 static const RegisterInfo
121 g_register_infos[] =
122 {
123     // General purpose registers.             eh_frame,                 DWARF,              Generic,    Process Plugin
124     DEFINE_GPR(r0,       nullptr, dwarf_r0,    dwarf_r0,    LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
125     DEFINE_GPR(r1,       "sp",    dwarf_r1,    dwarf_r1,    LLDB_REGNUM_GENERIC_SP, LLDB_INVALID_REGNUM),
126     DEFINE_GPR(r2,       nullptr, dwarf_r2,    dwarf_r2,    LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
127     DEFINE_GPR(r3,       "arg1",  dwarf_r3,    dwarf_r3,    LLDB_REGNUM_GENERIC_ARG1, LLDB_INVALID_REGNUM),
128     DEFINE_GPR(r4,       "arg2",  dwarf_r4,    dwarf_r4,    LLDB_REGNUM_GENERIC_ARG2 ,LLDB_INVALID_REGNUM),
129     DEFINE_GPR(r5,       "arg3",  dwarf_r5,    dwarf_r5,    LLDB_REGNUM_GENERIC_ARG3, LLDB_INVALID_REGNUM),
130     DEFINE_GPR(r6,       "arg4",  dwarf_r6,    dwarf_r6,    LLDB_REGNUM_GENERIC_ARG4, LLDB_INVALID_REGNUM),
131     DEFINE_GPR(r7,       "arg5",  dwarf_r7,    dwarf_r7,    LLDB_REGNUM_GENERIC_ARG5, LLDB_INVALID_REGNUM),
132     DEFINE_GPR(r8,       "arg6",  dwarf_r8,    dwarf_r8,    LLDB_REGNUM_GENERIC_ARG6, LLDB_INVALID_REGNUM),
133     DEFINE_GPR(r9,       "arg7",  dwarf_r9,    dwarf_r9,    LLDB_REGNUM_GENERIC_ARG7, LLDB_INVALID_REGNUM),
134     DEFINE_GPR(r10,      "arg8",  dwarf_r10,   dwarf_r10,   LLDB_REGNUM_GENERIC_ARG8, LLDB_INVALID_REGNUM),
135     DEFINE_GPR(r11,      nullptr, dwarf_r11,   dwarf_r11,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
136     DEFINE_GPR(r12,      nullptr, dwarf_r12,   dwarf_r12,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
137     DEFINE_GPR(r13,      nullptr, dwarf_r13,   dwarf_r13,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
138     DEFINE_GPR(r14,      nullptr, dwarf_r14,   dwarf_r14,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
139     DEFINE_GPR(r15,      nullptr, dwarf_r15,   dwarf_r15,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
140     DEFINE_GPR(r16,      nullptr, dwarf_r16,   dwarf_r16,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
141     DEFINE_GPR(r17,      nullptr, dwarf_r17,   dwarf_r17,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
142     DEFINE_GPR(r18,      nullptr, dwarf_r18,   dwarf_r18,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
143     DEFINE_GPR(r19,      nullptr, dwarf_r19,   dwarf_r19,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
144     DEFINE_GPR(r20,      nullptr, dwarf_r20,   dwarf_r20,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
145     DEFINE_GPR(r21,      nullptr, dwarf_r21,   dwarf_r21,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
146     DEFINE_GPR(r22,      nullptr, dwarf_r22,   dwarf_r22,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
147     DEFINE_GPR(r23,      nullptr, dwarf_r23,   dwarf_r23,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
148     DEFINE_GPR(r24,      nullptr, dwarf_r24,   dwarf_r24,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
149     DEFINE_GPR(r25,      nullptr, dwarf_r25,   dwarf_r25,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
150     DEFINE_GPR(r26,      nullptr, dwarf_r26,   dwarf_r26,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
151     DEFINE_GPR(r27,      nullptr, dwarf_r27,   dwarf_r27,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
152     DEFINE_GPR(r28,      nullptr, dwarf_r28,   dwarf_r28,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
153     DEFINE_GPR(r29,      nullptr, dwarf_r29,   dwarf_r29,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
154     DEFINE_GPR(r30,      nullptr, dwarf_r30,   dwarf_r30,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
155     DEFINE_GPR(r31,      nullptr, dwarf_r31,   dwarf_r31,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
156     DEFINE_GPR(lr,       "lr",    dwarf_lr,    dwarf_lr,    LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM),
157     DEFINE_GPR(cr,       "cr",    dwarf_cr,    dwarf_cr,    LLDB_REGNUM_GENERIC_FLAGS, LLDB_INVALID_REGNUM),
158     DEFINE_GPR(xer,      "xer",   dwarf_xer,   dwarf_xer,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
159     DEFINE_GPR(ctr,      "ctr",   dwarf_ctr,   dwarf_ctr,   LLDB_INVALID_REGNUM,    LLDB_INVALID_REGNUM),
160     DEFINE_GPR(pc,       "pc",    dwarf_pc,    dwarf_pc,    LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_REGNUM),
161     { nullptr, nullptr, 8, 0, eEncodingUint, eFormatHex, { dwarf_cfa, dwarf_cfa, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr }
162 };
163
164 static const uint32_t k_num_register_infos = llvm::array_lengthof(g_register_infos);
165
166 const lldb_private::RegisterInfo *
167 ABISysV_ppc::GetRegisterInfoArray (uint32_t &count)
168 {
169     count = k_num_register_infos;
170     return g_register_infos;
171 }
172
173 size_t
174 ABISysV_ppc::GetRedZoneSize () const
175 {
176     return 224;
177 }
178
179 //------------------------------------------------------------------
180 // Static Functions
181 //------------------------------------------------------------------
182
183 ABISP
184 ABISysV_ppc::CreateInstance (const ArchSpec &arch)
185 {
186     static ABISP g_abi_sp;
187     if (arch.GetTriple().getArch() == llvm::Triple::ppc)
188     {
189         if (!g_abi_sp)
190             g_abi_sp.reset (new ABISysV_ppc);
191         return g_abi_sp;
192     }
193     return ABISP();
194 }
195
196 bool
197 ABISysV_ppc::PrepareTrivialCall (Thread &thread,
198                                     addr_t sp,
199                                     addr_t func_addr,
200                                     addr_t return_addr,
201                                     llvm::ArrayRef<addr_t> args) const
202 {
203     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
204
205     if (log)
206     {
207         StreamString s;
208         s.Printf("ABISysV_ppc::PrepareTrivialCall (tid = 0x%" PRIx64 ", sp = 0x%" PRIx64 ", func_addr = 0x%" PRIx64 ", return_addr = 0x%" PRIx64,
209                     thread.GetID(),
210                     (uint64_t)sp,
211                     (uint64_t)func_addr,
212                     (uint64_t)return_addr);
213
214         for (size_t i = 0; i < args.size(); ++i)
215             s.Printf (", arg%" PRIu64 " = 0x%" PRIx64, static_cast<uint64_t>(i + 1), args[i]);
216         s.PutCString (")");
217         log->PutCString(s.GetString().c_str());
218     }
219
220     RegisterContext *reg_ctx = thread.GetRegisterContext().get();
221     if (!reg_ctx)
222         return false;
223
224     const RegisterInfo *reg_info = nullptr;
225
226     if (args.size() > 8) // TODO handle more than 8 arguments
227         return false;
228
229     for (size_t i = 0; i < args.size(); ++i)
230     {
231         reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG1 + i);
232         if (log)
233             log->Printf("About to write arg%" PRIu64 " (0x%" PRIx64 ") into %s", static_cast<uint64_t>(i + 1), args[i], reg_info->name);
234         if (!reg_ctx->WriteRegisterFromUnsigned(reg_info, args[i]))
235             return false;
236     }
237
238     // First, align the SP
239
240     if (log)
241         log->Printf("16-byte aligning SP: 0x%" PRIx64 " to 0x%" PRIx64, (uint64_t)sp, (uint64_t)(sp & ~0xfull));
242
243     sp &= ~(0xfull); // 16-byte alignment
244
245     sp -= 8;
246
247     Error error;
248     const RegisterInfo *pc_reg_info = reg_ctx->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
249     const RegisterInfo *sp_reg_info = reg_ctx->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP);
250     ProcessSP process_sp (thread.GetProcess());
251
252     RegisterValue reg_value;
253
254 #if 0
255     // This code adds an extra frame so that we don't lose the function that we came from
256     // by pushing the PC and the FP and then writing the current FP to point to the FP value
257     // we just pushed. It is disabled for now until the stack backtracing code can be debugged.
258
259     // Save current PC
260     const RegisterInfo *fp_reg_info = reg_ctx->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP);
261     if (reg_ctx->ReadRegister(pc_reg_info, reg_value))
262     {
263         if (log)
264             log->Printf("Pushing the current PC onto the stack: 0x%" PRIx64 ": 0x%" PRIx64, (uint64_t)sp, reg_value.GetAsUInt64());
265
266         if (!process_sp->WritePointerToMemory(sp, reg_value.GetAsUInt64(), error))
267             return false;
268
269         sp -= 8;
270
271         // Save current FP
272         if (reg_ctx->ReadRegister(fp_reg_info, reg_value))
273         {
274             if (log)
275                 log->Printf("Pushing the current FP onto the stack: 0x%" PRIx64 ": 0x%" PRIx64, (uint64_t)sp, reg_value.GetAsUInt64());
276
277             if (!process_sp->WritePointerToMemory(sp, reg_value.GetAsUInt64(), error))
278                 return false;
279         }
280         // Setup FP backchain
281         reg_value.SetUInt64 (sp);
282
283         if (log)
284             log->Printf("Writing FP:  0x%" PRIx64 " (for FP backchain)", reg_value.GetAsUInt64());
285
286         if (!reg_ctx->WriteRegister(fp_reg_info, reg_value))
287         {
288             return false;
289         }
290
291         sp -= 8;
292     }
293 #endif
294
295     if (log)
296         log->Printf("Pushing the return address onto the stack: 0x%" PRIx64 ": 0x%" PRIx64, (uint64_t)sp, (uint64_t)return_addr);
297
298     // Save return address onto the stack
299     if (!process_sp->WritePointerToMemory(sp, return_addr, error))
300         return false;
301
302     // %r1 is set to the actual stack value.
303
304     if (log)
305         log->Printf("Writing SP: 0x%" PRIx64, (uint64_t)sp);
306
307     if (!reg_ctx->WriteRegisterFromUnsigned (sp_reg_info, sp))
308         return false;
309
310     // %pc is set to the address of the called function.
311
312     if (log)
313         log->Printf("Writing IP: 0x%" PRIx64, (uint64_t)func_addr);
314
315     if (!reg_ctx->WriteRegisterFromUnsigned (pc_reg_info, func_addr))
316         return false;
317
318     return true;
319 }
320
321 static bool ReadIntegerArgument(Scalar           &scalar,
322                                 unsigned int     bit_width,
323                                 bool             is_signed,
324                                 Thread           &thread,
325                                 uint32_t         *argument_register_ids,
326                                 unsigned int     &current_argument_register,
327                                 addr_t           &current_stack_argument)
328 {
329     if (bit_width > 64)
330         return false; // Scalar can't hold large integer arguments
331
332     if (current_argument_register < 6)
333     {
334         scalar = thread.GetRegisterContext()->ReadRegisterAsUnsigned(argument_register_ids[current_argument_register], 0);
335         current_argument_register++;
336         if (is_signed)
337             scalar.SignExtend (bit_width);
338     }
339     else
340     {
341         uint32_t byte_size = (bit_width + (8-1))/8;
342         Error error;
343         if (thread.GetProcess()->ReadScalarIntegerFromMemory(current_stack_argument, byte_size, is_signed, scalar, error))
344         {
345             current_stack_argument += byte_size;
346             return true;
347         }
348         return false;
349     }
350     return true;
351 }
352
353 bool
354 ABISysV_ppc::GetArgumentValues (Thread &thread,
355                                 ValueList &values) const
356 {
357     unsigned int num_values = values.GetSize();
358     unsigned int value_index;
359
360     // Extract the register context so we can read arguments from registers
361
362     RegisterContext *reg_ctx = thread.GetRegisterContext().get();
363
364     if (!reg_ctx)
365         return false;
366
367     // Get the pointer to the first stack argument so we have a place to start
368     // when reading data
369
370     addr_t sp = reg_ctx->GetSP(0);
371
372     if (!sp)
373         return false;
374
375     addr_t current_stack_argument = sp + 48; // jump over return address
376
377     uint32_t argument_register_ids[8];
378
379     argument_register_ids[0] = reg_ctx->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG1)->kinds[eRegisterKindLLDB];
380     argument_register_ids[1] = reg_ctx->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG2)->kinds[eRegisterKindLLDB];
381     argument_register_ids[2] = reg_ctx->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG3)->kinds[eRegisterKindLLDB];
382     argument_register_ids[3] = reg_ctx->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG4)->kinds[eRegisterKindLLDB];
383     argument_register_ids[4] = reg_ctx->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG5)->kinds[eRegisterKindLLDB];
384     argument_register_ids[5] = reg_ctx->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG6)->kinds[eRegisterKindLLDB];
385     argument_register_ids[6] = reg_ctx->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG7)->kinds[eRegisterKindLLDB];
386     argument_register_ids[7] = reg_ctx->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG8)->kinds[eRegisterKindLLDB];
387
388     unsigned int current_argument_register = 0;
389
390     for (value_index = 0;
391          value_index < num_values;
392          ++value_index)
393     {
394         Value *value = values.GetValueAtIndex(value_index);
395
396         if (!value)
397             return false;
398
399         // We currently only support extracting values with Clang QualTypes.
400         // Do we care about others?
401         CompilerType compiler_type = value->GetCompilerType();
402         if (!compiler_type)
403             return false;
404         bool is_signed;
405
406         if (compiler_type.IsIntegerOrEnumerationType (is_signed))
407         {
408             ReadIntegerArgument(value->GetScalar(),
409                                 compiler_type.GetBitSize(&thread),
410                                 is_signed,
411                                 thread,
412                                 argument_register_ids,
413                                 current_argument_register,
414                                 current_stack_argument);
415         }
416         else if (compiler_type.IsPointerType ())
417         {
418             ReadIntegerArgument(value->GetScalar(),
419                                 compiler_type.GetBitSize(&thread),
420                                 false,
421                                 thread,
422                                 argument_register_ids,
423                                 current_argument_register,
424                                 current_stack_argument);
425         }
426     }
427
428     return true;
429 }
430
431 Error
432 ABISysV_ppc::SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value_sp)
433 {
434     Error error;
435     if (!new_value_sp)
436     {
437         error.SetErrorString("Empty value object for return value.");
438         return error;
439     }
440
441     CompilerType compiler_type = new_value_sp->GetCompilerType();
442     if (!compiler_type)
443     {
444         error.SetErrorString ("Null clang type for return value.");
445         return error;
446     }
447
448     Thread *thread = frame_sp->GetThread().get();
449
450     bool is_signed;
451     uint32_t count;
452     bool is_complex;
453
454     RegisterContext *reg_ctx = thread->GetRegisterContext().get();
455
456     bool set_it_simple = false;
457     if (compiler_type.IsIntegerOrEnumerationType (is_signed) || compiler_type.IsPointerType())
458     {
459         const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName("r3", 0);
460
461         DataExtractor data;
462         Error data_error;
463         size_t num_bytes = new_value_sp->GetData(data, data_error);
464         if (data_error.Fail())
465         {
466             error.SetErrorStringWithFormat("Couldn't convert return value to raw data: %s", data_error.AsCString());
467             return error;
468         }
469         lldb::offset_t offset = 0;
470         if (num_bytes <= 8)
471         {
472             uint64_t raw_value = data.GetMaxU64(&offset, num_bytes);
473
474             if (reg_ctx->WriteRegisterFromUnsigned (reg_info, raw_value))
475                 set_it_simple = true;
476         }
477         else
478         {
479             error.SetErrorString("We don't support returning longer than 64 bit integer values at present.");
480         }
481     }
482     else if (compiler_type.IsFloatingPointType (count, is_complex))
483     {
484         if (is_complex)
485             error.SetErrorString ("We don't support returning complex values at present");
486         else
487         {
488             size_t bit_width = compiler_type.GetBitSize(frame_sp.get());
489             if (bit_width <= 64)
490             {
491                 DataExtractor data;
492                 Error data_error;
493                 size_t num_bytes = new_value_sp->GetData(data, data_error);
494                 if (data_error.Fail())
495                 {
496                     error.SetErrorStringWithFormat("Couldn't convert return value to raw data: %s", data_error.AsCString());
497                     return error;
498                 }
499
500                 unsigned char buffer[16];
501                 ByteOrder byte_order = data.GetByteOrder();
502
503                 data.CopyByteOrderedData (0, num_bytes, buffer, 16, byte_order);
504                 set_it_simple = true;
505             }
506             else
507             {
508                 // FIXME - don't know how to do 80 bit long doubles yet.
509                 error.SetErrorString ("We don't support returning float values > 64 bits at present");
510             }
511         }
512     }
513
514     if (!set_it_simple)
515     {
516         // Okay we've got a structure or something that doesn't fit in a simple register.
517         // We should figure out where it really goes, but we don't support this yet.
518         error.SetErrorString ("We only support setting simple integer and float return types at present.");
519     }
520
521     return error;
522 }
523
524 ValueObjectSP
525 ABISysV_ppc::GetReturnValueObjectSimple (Thread &thread,
526                                          CompilerType &return_compiler_type) const
527 {
528     ValueObjectSP return_valobj_sp;
529     Value value;
530
531     if (!return_compiler_type)
532         return return_valobj_sp;
533
534     //value.SetContext (Value::eContextTypeClangType, return_value_type);
535     value.SetCompilerType (return_compiler_type);
536
537     RegisterContext *reg_ctx = thread.GetRegisterContext().get();
538     if (!reg_ctx)
539         return return_valobj_sp;
540
541     const uint32_t type_flags = return_compiler_type.GetTypeInfo ();
542     if (type_flags & eTypeIsScalar)
543     {
544         value.SetValueType(Value::eValueTypeScalar);
545
546         bool success = false;
547         if (type_flags & eTypeIsInteger)
548         {
549             // Extract the register context so we can read arguments from registers
550
551             const size_t byte_size = return_compiler_type.GetByteSize(nullptr);
552             uint64_t raw_value = thread.GetRegisterContext()->ReadRegisterAsUnsigned(reg_ctx->GetRegisterInfoByName("r3", 0), 0);
553             const bool is_signed = (type_flags & eTypeIsSigned) != 0;
554             switch (byte_size)
555             {
556             default:
557                 break;
558
559             case sizeof(uint64_t):
560                 if (is_signed)
561                     value.GetScalar() = (int64_t)(raw_value);
562                 else
563                     value.GetScalar() = (uint64_t)(raw_value);
564                 success = true;
565                 break;
566
567             case sizeof(uint32_t):
568                 if (is_signed)
569                     value.GetScalar() = (int32_t)(raw_value & UINT32_MAX);
570                 else
571                     value.GetScalar() = (uint32_t)(raw_value & UINT32_MAX);
572                 success = true;
573                 break;
574
575             case sizeof(uint16_t):
576                 if (is_signed)
577                     value.GetScalar() = (int16_t)(raw_value & UINT16_MAX);
578                 else
579                     value.GetScalar() = (uint16_t)(raw_value & UINT16_MAX);
580                 success = true;
581                 break;
582
583             case sizeof(uint8_t):
584                 if (is_signed)
585                     value.GetScalar() = (int8_t)(raw_value & UINT8_MAX);
586                 else
587                     value.GetScalar() = (uint8_t)(raw_value & UINT8_MAX);
588                 success = true;
589                 break;
590             }
591         }
592         else if (type_flags & eTypeIsFloat)
593         {
594             if (type_flags & eTypeIsComplex)
595             {
596                 // Don't handle complex yet.
597             }
598             else
599             {
600                 const size_t byte_size = return_compiler_type.GetByteSize(nullptr);
601                 if (byte_size <= sizeof(long double))
602                 {
603                     const RegisterInfo *f1_info = reg_ctx->GetRegisterInfoByName("f1", 0);
604                     RegisterValue f1_value;
605                     if (reg_ctx->ReadRegister (f1_info, f1_value))
606                     {
607                         DataExtractor data;
608                         if (f1_value.GetData(data))
609                         {
610                             lldb::offset_t offset = 0;
611                             if (byte_size == sizeof(float))
612                             {
613                                 value.GetScalar() = (float) data.GetFloat(&offset);
614                                 success = true;
615                             }
616                             else if (byte_size == sizeof(double))
617                             {
618                                 value.GetScalar() = (double) data.GetDouble(&offset);
619                                 success = true;
620                             }
621                         }
622                     }
623                 }
624             }
625         }
626
627         if (success)
628             return_valobj_sp = ValueObjectConstResult::Create (thread.GetStackFrameAtIndex(0).get(),
629                                                                value,
630                                                                ConstString(""));
631     }
632     else if (type_flags & eTypeIsPointer)
633     {
634         unsigned r3_id = reg_ctx->GetRegisterInfoByName("r3", 0)->kinds[eRegisterKindLLDB];
635         value.GetScalar() = (uint64_t)thread.GetRegisterContext()->ReadRegisterAsUnsigned(r3_id, 0);
636         value.SetValueType(Value::eValueTypeScalar);
637         return_valobj_sp = ValueObjectConstResult::Create (thread.GetStackFrameAtIndex(0).get(),
638                                                            value,
639                                                            ConstString(""));
640     }
641     else if (type_flags & eTypeIsVector)
642     {
643         const size_t byte_size = return_compiler_type.GetByteSize(nullptr);
644         if (byte_size > 0)
645         {
646             const RegisterInfo *altivec_reg = reg_ctx->GetRegisterInfoByName("v2", 0);
647             if (altivec_reg)
648             {
649                 if (byte_size <= altivec_reg->byte_size)
650                 {
651                     ProcessSP process_sp (thread.GetProcess());
652                     if (process_sp)
653                     {
654                         std::unique_ptr<DataBufferHeap> heap_data_ap (new DataBufferHeap(byte_size, 0));
655                         const ByteOrder byte_order = process_sp->GetByteOrder();
656                         RegisterValue reg_value;
657                         if (reg_ctx->ReadRegister(altivec_reg, reg_value))
658                         {
659                             Error error;
660                             if (reg_value.GetAsMemoryData (altivec_reg,
661                                                            heap_data_ap->GetBytes(),
662                                                            heap_data_ap->GetByteSize(),
663                                                            byte_order,
664                                                            error))
665                             {
666                                 DataExtractor data (DataBufferSP (heap_data_ap.release()),
667                                                     byte_order,
668                                                     process_sp->GetTarget().GetArchitecture().GetAddressByteSize());
669                                 return_valobj_sp = ValueObjectConstResult::Create (&thread,
670                                                                                    return_compiler_type,
671                                                                                    ConstString(""),
672                                                                                    data);
673                             }
674                         }
675                     }
676                 }
677             }
678         }
679     }
680
681     return return_valobj_sp;
682 }
683
684 ValueObjectSP
685 ABISysV_ppc::GetReturnValueObjectImpl (Thread &thread, CompilerType &return_compiler_type) const
686 {
687     ValueObjectSP return_valobj_sp;
688
689     if (!return_compiler_type)
690         return return_valobj_sp;
691
692     ExecutionContext exe_ctx (thread.shared_from_this());
693     return_valobj_sp = GetReturnValueObjectSimple(thread, return_compiler_type);
694     if (return_valobj_sp)
695         return return_valobj_sp;
696
697     RegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
698     if (!reg_ctx_sp)
699         return return_valobj_sp;
700
701     const size_t bit_width = return_compiler_type.GetBitSize(&thread);
702     if (return_compiler_type.IsAggregateType())
703     {
704         Target *target = exe_ctx.GetTargetPtr();
705         bool is_memory = true;
706         if (bit_width <= 128)
707         {
708             ByteOrder target_byte_order = target->GetArchitecture().GetByteOrder();
709             DataBufferSP data_sp (new DataBufferHeap(16, 0));
710             DataExtractor return_ext (data_sp,
711                                       target_byte_order,
712                                       target->GetArchitecture().GetAddressByteSize());
713
714             const RegisterInfo *r3_info = reg_ctx_sp->GetRegisterInfoByName("r3", 0);
715             const RegisterInfo *rdx_info = reg_ctx_sp->GetRegisterInfoByName("rdx", 0);
716
717             RegisterValue r3_value, rdx_value;
718             reg_ctx_sp->ReadRegister (r3_info, r3_value);
719             reg_ctx_sp->ReadRegister (rdx_info, rdx_value);
720
721             DataExtractor r3_data, rdx_data;
722
723             r3_value.GetData(r3_data);
724             rdx_value.GetData(rdx_data);
725
726             uint32_t fp_bytes = 0;       // Tracks how much of the xmm registers we've consumed so far
727             uint32_t integer_bytes = 0;  // Tracks how much of the r3/rds registers we've consumed so far
728
729             const uint32_t num_children = return_compiler_type.GetNumFields ();
730
731             // Since we are in the small struct regime, assume we are not in memory.
732             is_memory = false;
733
734             for (uint32_t idx = 0; idx < num_children; idx++)
735             {
736                 std::string name;
737                 uint64_t field_bit_offset = 0;
738                 bool is_signed;
739                 bool is_complex;
740                 uint32_t count;
741
742                 CompilerType field_compiler_type = return_compiler_type.GetFieldAtIndex(idx, name, &field_bit_offset, nullptr, nullptr);
743                 const size_t field_bit_width = field_compiler_type.GetBitSize(&thread);
744
745                 // If there are any unaligned fields, this is stored in memory.
746                 if (field_bit_offset % field_bit_width != 0)
747                 {
748                     is_memory = true;
749                     break;
750                 }
751
752                 uint32_t field_byte_width = field_bit_width/8;
753                 uint32_t field_byte_offset = field_bit_offset/8;
754
755                 DataExtractor *copy_from_extractor = nullptr;
756                 uint32_t       copy_from_offset    = 0;
757
758                 if (field_compiler_type.IsIntegerOrEnumerationType (is_signed) || field_compiler_type.IsPointerType ())
759                 {
760                     if (integer_bytes < 8)
761                     {
762                         if (integer_bytes + field_byte_width <= 8)
763                         {
764                             // This is in RAX, copy from register to our result structure:
765                             copy_from_extractor = &r3_data;
766                             copy_from_offset = integer_bytes;
767                             integer_bytes += field_byte_width;
768                         }
769                         else
770                         {
771                             // The next field wouldn't fit in the remaining space, so we pushed it to rdx.
772                             copy_from_extractor = &rdx_data;
773                             copy_from_offset = 0;
774                             integer_bytes = 8 + field_byte_width;
775                         }
776                     }
777                     else if (integer_bytes + field_byte_width <= 16)
778                     {
779                         copy_from_extractor = &rdx_data;
780                         copy_from_offset = integer_bytes - 8;
781                         integer_bytes += field_byte_width;
782                     }
783                     else
784                     {
785                         // The last field didn't fit.  I can't see how that would happen w/o the overall size being
786                         // greater than 16 bytes.  For now, return a nullptr return value object.
787                         return return_valobj_sp;
788                     }
789                 }
790                 else if (field_compiler_type.IsFloatingPointType (count, is_complex))
791                 {
792                     // Structs with long doubles are always passed in memory.
793                     if (field_bit_width == 128)
794                     {
795                         is_memory = true;
796                         break;
797                     }
798                     else if (field_bit_width == 64)
799                     {
800                         copy_from_offset = 0;
801                         fp_bytes += field_byte_width;
802                     }
803                     else if (field_bit_width == 32)
804                     {
805                         // This one is kind of complicated.  If we are in an "eightbyte" with another float, we'll
806                         // be stuffed into an xmm register with it.  If we are in an "eightbyte" with one or more ints,
807                         // then we will be stuffed into the appropriate GPR with them.
808                         bool in_gpr;
809                         if (field_byte_offset % 8 == 0)
810                         {
811                             // We are at the beginning of one of the eightbytes, so check the next element (if any)
812                             if (idx == num_children - 1)
813                                 in_gpr = false;
814                             else
815                             {
816                                 uint64_t next_field_bit_offset = 0;
817                                 CompilerType next_field_compiler_type = return_compiler_type.GetFieldAtIndex (idx + 1,
818                                                                                                         name,
819                                                                                                         &next_field_bit_offset,
820                                                                                                         nullptr,
821                                                                                                         nullptr);
822                                 if (next_field_compiler_type.IsIntegerOrEnumerationType (is_signed))
823                                     in_gpr = true;
824                                 else
825                                 {
826                                     copy_from_offset = 0;
827                                     in_gpr = false;
828                                 }
829                             }
830                         }
831                         else if (field_byte_offset % 4 == 0)
832                         {
833                             // We are inside of an eightbyte, so see if the field before us is floating point:
834                             // This could happen if somebody put padding in the structure.
835                             if (idx == 0)
836                                 in_gpr = false;
837                             else
838                             {
839                                 uint64_t prev_field_bit_offset = 0;
840                                 CompilerType prev_field_compiler_type = return_compiler_type.GetFieldAtIndex (idx - 1,
841                                                                                                         name,
842                                                                                                         &prev_field_bit_offset,
843                                                                                                         nullptr,
844                                                                                                         nullptr);
845                                 if (prev_field_compiler_type.IsIntegerOrEnumerationType (is_signed))
846                                     in_gpr = true;
847                                 else
848                                 {
849                                     copy_from_offset = 4;
850                                     in_gpr = false;
851                                 }
852                             }
853                         }
854                         else
855                         {
856                             is_memory = true;
857                             continue;
858                         }
859
860                         // Okay, we've figured out whether we are in GPR or XMM, now figure out which one.
861                         if (in_gpr)
862                         {
863                             if (integer_bytes < 8)
864                             {
865                                 // This is in RAX, copy from register to our result structure:
866                                 copy_from_extractor = &r3_data;
867                                 copy_from_offset = integer_bytes;
868                                 integer_bytes += field_byte_width;
869                             }
870                             else
871                             {
872                                 copy_from_extractor = &rdx_data;
873                                 copy_from_offset = integer_bytes - 8;
874                                 integer_bytes += field_byte_width;
875                             }
876                         }
877                         else
878                         {
879                             fp_bytes += field_byte_width;
880                         }
881                     }
882                 }
883
884                 // These two tests are just sanity checks.  If I somehow get the
885                 // type calculation wrong above it is better to just return nothing
886                 // than to assert or crash.
887                 if (!copy_from_extractor)
888                     return return_valobj_sp;
889                 if (copy_from_offset + field_byte_width > copy_from_extractor->GetByteSize())
890                     return return_valobj_sp;
891
892                 copy_from_extractor->CopyByteOrderedData (copy_from_offset,
893                                                           field_byte_width,
894                                                           data_sp->GetBytes() + field_byte_offset,
895                                                           field_byte_width,
896                                                           target_byte_order);
897             }
898
899             if (!is_memory)
900             {
901                 // The result is in our data buffer.  Let's make a variable object out of it:
902                 return_valobj_sp = ValueObjectConstResult::Create (&thread,
903                                                                    return_compiler_type,
904                                                                    ConstString(""),
905                                                                    return_ext);
906             }
907         }
908
909         // FIXME: This is just taking a guess, r3 may very well no longer hold the return storage location.
910         // If we are going to do this right, when we make a new frame we should check to see if it uses a memory
911         // return, and if we are at the first instruction and if so stash away the return location.  Then we would
912         // only return the memory return value if we know it is valid.
913
914         if (is_memory)
915         {
916             unsigned r3_id = reg_ctx_sp->GetRegisterInfoByName("r3", 0)->kinds[eRegisterKindLLDB];
917             lldb::addr_t storage_addr = (uint64_t)thread.GetRegisterContext()->ReadRegisterAsUnsigned(r3_id, 0);
918             return_valobj_sp = ValueObjectMemory::Create(&thread,
919                                                          "",
920                                                          Address(storage_addr, nullptr),
921                                                          return_compiler_type);
922         }
923     }
924
925     return return_valobj_sp;
926 }
927
928 bool
929 ABISysV_ppc::CreateFunctionEntryUnwindPlan (UnwindPlan &unwind_plan)
930 {
931     unwind_plan.Clear();
932     unwind_plan.SetRegisterKind (eRegisterKindDWARF);
933
934     uint32_t lr_reg_num = dwarf_lr;
935     uint32_t sp_reg_num = dwarf_r1;
936     uint32_t pc_reg_num = dwarf_pc;
937
938     UnwindPlan::RowSP row(new UnwindPlan::Row);
939
940     // Our Call Frame Address is the stack pointer value
941     row->GetCFAValue().SetIsRegisterPlusOffset (sp_reg_num, 0);
942
943     // The previous PC is in the LR
944     row->SetRegisterLocationToRegister(pc_reg_num, lr_reg_num, true);
945     unwind_plan.AppendRow (row);
946
947     // All other registers are the same.
948
949     unwind_plan.SetSourceName ("ppc at-func-entry default");
950     unwind_plan.SetSourcedFromCompiler (eLazyBoolNo);
951
952     return true;
953 }
954
955 bool
956 ABISysV_ppc::CreateDefaultUnwindPlan (UnwindPlan &unwind_plan)
957 {
958     unwind_plan.Clear();
959     unwind_plan.SetRegisterKind (eRegisterKindDWARF);
960
961     uint32_t sp_reg_num = dwarf_r1;
962     uint32_t pc_reg_num = dwarf_lr;
963
964     UnwindPlan::RowSP row(new UnwindPlan::Row);
965
966     const int32_t ptr_size = 4;
967     row->GetCFAValue().SetIsRegisterDereferenced (sp_reg_num);
968
969     row->SetRegisterLocationToAtCFAPlusOffset(pc_reg_num, ptr_size * 1, true);
970     row->SetRegisterLocationToIsCFAPlusOffset(sp_reg_num, 0, true);
971
972     unwind_plan.AppendRow (row);
973     unwind_plan.SetSourceName ("ppc default unwind plan");
974     unwind_plan.SetSourcedFromCompiler (eLazyBoolNo);
975     unwind_plan.SetUnwindPlanValidAtAllInstructions (eLazyBoolNo);
976     unwind_plan.SetReturnAddressRegister(dwarf_lr);
977     return true;
978 }
979
980 bool
981 ABISysV_ppc::RegisterIsVolatile (const RegisterInfo *reg_info)
982 {
983     return !RegisterIsCalleeSaved (reg_info);
984 }
985
986 // See "Register Usage" in the
987 // "System V Application Binary Interface"
988 // "64-bit PowerPC ELF Application Binary Interface Supplement"
989 // current version is 1.9 released 2004 at http://refspecs.linuxfoundation.org/ELF/ppc/PPC-elf64abi-1.9.pdf
990
991 bool
992 ABISysV_ppc::RegisterIsCalleeSaved (const RegisterInfo *reg_info)
993 {
994     if (reg_info)
995     {
996         // Preserved registers are :
997         //    r1,r2,r13-r31
998         //    f14-f31 (not yet)
999         //    v20-v31 (not yet)
1000         //    vrsave (not yet)
1001
1002         const char *name = reg_info->name;
1003         if (name[0] == 'r')
1004         {
1005             if ((name[1] == '1' || name[1] == '2') && name[2] == '\0')
1006                 return true;
1007             if (name[1] == '1' && name[2] > '2')
1008                 return true;
1009             if ((name[1] == '2' || name[1] == '3') && name[2] != '\0')
1010                 return true;
1011         }
1012
1013         if (name[0] == 'f' && name[1] >= '0' && name[1] <= '9')
1014         {
1015             if (name[3] == '1' && name[4] >= '4')
1016                 return true;
1017             if ((name[3] == '2' || name[3] == '3') && name[4] != '\0')
1018                 return true;
1019         }
1020
1021         if (name[0] == 's' && name[1] == 'p' && name[2] == '\0')   // sp
1022             return true;
1023         if (name[0] == 'f' && name[1] == 'p' && name[2] == '\0')   // fp
1024             return true;
1025         if (name[0] == 'p' && name[1] == 'c' && name[2] == '\0')   // pc
1026             return true;
1027     }
1028     return false;
1029 }
1030
1031 void
1032 ABISysV_ppc::Initialize()
1033 {
1034     PluginManager::RegisterPlugin (GetPluginNameStatic(),
1035                                    "System V ABI for ppc targets",
1036                                    CreateInstance);
1037 }
1038
1039 void
1040 ABISysV_ppc::Terminate()
1041 {
1042     PluginManager::UnregisterPlugin (CreateInstance);
1043 }
1044
1045 lldb_private::ConstString
1046 ABISysV_ppc::GetPluginNameStatic()
1047 {
1048     static ConstString g_name("sysv-ppc");
1049     return g_name;
1050 }
1051
1052 //------------------------------------------------------------------
1053 // PluginInterface protocol
1054 //------------------------------------------------------------------
1055
1056 lldb_private::ConstString
1057 ABISysV_ppc::GetPluginName()
1058 {
1059     return GetPluginNameStatic();
1060 }
1061
1062 uint32_t
1063 ABISysV_ppc::GetPluginVersion()
1064 {
1065     return 1;
1066 }