xref: /NextBSD/contrib/llvm/tools/lldb/source/Expression/IRForTarget.cpp (revision 84d351007654069f9643c8e4b4802a7f5f08ee42)
1 //===-- IRForTarget.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 "lldb/Expression/IRForTarget.h"
11 
12 #include "llvm/Support/raw_ostream.h"
13 #include "llvm/IR/Constants.h"
14 #include "llvm/IR/DataLayout.h"
15 #include "llvm/IR/InstrTypes.h"
16 #include "llvm/IR/Instructions.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/IR/LegacyPassManager.h"
20 #include "llvm/Transforms/IPO.h"
21 #include "llvm/IR/Metadata.h"
22 #include "llvm/IR/ValueSymbolTable.h"
23 
24 #include "clang/AST/ASTContext.h"
25 
26 #include "lldb/Core/dwarf.h"
27 #include "lldb/Core/ConstString.h"
28 #include "lldb/Core/DataBufferHeap.h"
29 #include "lldb/Core/Log.h"
30 #include "lldb/Core/Scalar.h"
31 #include "lldb/Core/StreamString.h"
32 #include "lldb/Expression/ClangExpressionDeclMap.h"
33 #include "lldb/Expression/IRExecutionUnit.h"
34 #include "lldb/Expression/IRInterpreter.h"
35 #include "lldb/Host/Endian.h"
36 #include "lldb/Symbol/ClangASTContext.h"
37 #include "lldb/Symbol/ClangASTType.h"
38 #include "lldb/Target/CPPLanguageRuntime.h"
39 
40 #include <map>
41 
42 using namespace llvm;
43 
44 static char ID;
45 
StaticDataAllocator(lldb_private::IRExecutionUnit & execution_unit)46 IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) :
47     m_execution_unit(execution_unit),
48     m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()),
49     m_allocation(LLDB_INVALID_ADDRESS)
50 {
51 }
52 
FunctionValueCache(Maker const & maker)53 IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) :
54     m_maker(maker),
55     m_values()
56 {
57 }
58 
~FunctionValueCache()59 IRForTarget::FunctionValueCache::~FunctionValueCache()
60 {
61 }
62 
63 llvm::Value *
GetValue(llvm::Function * function)64 IRForTarget::FunctionValueCache::GetValue(llvm::Function *function)
65 {
66     if (!m_values.count(function))
67     {
68         llvm::Value *ret = m_maker(function);
69         m_values[function] = ret;
70         return ret;
71     }
72     return m_values[function];
73 }
74 
75 lldb::addr_t
Allocate()76 IRForTarget::StaticDataAllocator::Allocate()
77 {
78     lldb_private::Error err;
79 
80     if (m_allocation != LLDB_INVALID_ADDRESS)
81     {
82         m_execution_unit.FreeNow(m_allocation);
83         m_allocation = LLDB_INVALID_ADDRESS;
84     }
85 
86     m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
87 
88     return m_allocation;
89 }
90 
91 lldb::TargetSP
GetTarget()92 IRForTarget::StaticDataAllocator::GetTarget()
93 {
94     return m_execution_unit.GetTarget();
95 }
96 
97 static llvm::Value *
FindEntryInstruction(llvm::Function * function)98 FindEntryInstruction (llvm::Function *function)
99 {
100     if (function->empty())
101         return NULL;
102 
103     return function->getEntryBlock().getFirstNonPHIOrDbg();
104 }
105 
IRForTarget(lldb_private::ClangExpressionDeclMap * decl_map,bool resolve_vars,lldb_private::IRExecutionUnit & execution_unit,lldb_private::Stream * error_stream,const char * func_name)106 IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
107                           bool resolve_vars,
108                           lldb_private::IRExecutionUnit &execution_unit,
109                           lldb_private::Stream *error_stream,
110                           const char *func_name) :
111     ModulePass(ID),
112     m_resolve_vars(resolve_vars),
113     m_func_name(func_name),
114     m_module(NULL),
115     m_decl_map(decl_map),
116     m_data_allocator(execution_unit),
117     m_CFStringCreateWithBytes(NULL),
118     m_sel_registerName(NULL),
119     m_intptr_ty(NULL),
120     m_error_stream(error_stream),
121     m_result_store(NULL),
122     m_result_is_pointer(false),
123     m_reloc_placeholder(NULL),
124     m_entry_instruction_finder (FindEntryInstruction)
125 {
126 }
127 
128 /* Handy utility functions used at several places in the code */
129 
130 static std::string
PrintValue(const Value * value,bool truncate=false)131 PrintValue(const Value *value, bool truncate = false)
132 {
133     std::string s;
134     if (value)
135     {
136         raw_string_ostream rso(s);
137         value->print(rso);
138         rso.flush();
139         if (truncate)
140             s.resize(s.length() - 1);
141     }
142     return s;
143 }
144 
145 static std::string
PrintType(const llvm::Type * type,bool truncate=false)146 PrintType(const llvm::Type *type, bool truncate = false)
147 {
148     std::string s;
149     raw_string_ostream rso(s);
150     type->print(rso);
151     rso.flush();
152     if (truncate)
153         s.resize(s.length() - 1);
154     return s;
155 }
156 
~IRForTarget()157 IRForTarget::~IRForTarget()
158 {
159 }
160 
161 bool
FixFunctionLinkage(llvm::Function & llvm_function)162 IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
163 {
164     llvm_function.setLinkage(GlobalValue::ExternalLinkage);
165 
166     std::string name = llvm_function.getName().str();
167 
168     return true;
169 }
170 
171 IRForTarget::LookupResult
GetFunctionAddress(llvm::Function * fun,uint64_t & fun_addr,lldb_private::ConstString & name,Constant ** & value_ptr)172 IRForTarget::GetFunctionAddress (llvm::Function *fun,
173                                  uint64_t &fun_addr,
174                                  lldb_private::ConstString &name,
175                                  Constant **&value_ptr)
176 {
177     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
178 
179     fun_addr = LLDB_INVALID_ADDRESS;
180     name.Clear();
181     value_ptr = NULL;
182 
183     if (fun->isIntrinsic())
184     {
185         Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
186 
187         switch (intrinsic_id)
188         {
189         default:
190             if (log)
191                 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
192 
193             if (m_error_stream)
194                 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
195 
196             return LookupResult::Fail;
197         case Intrinsic::memcpy:
198             {
199                 static lldb_private::ConstString g_memcpy_str ("memcpy");
200                 name = g_memcpy_str;
201             }
202             break;
203         case Intrinsic::memset:
204             {
205                 static lldb_private::ConstString g_memset_str ("memset");
206                 name = g_memset_str;
207             }
208             break;
209         case Intrinsic::dbg_declare:
210         case Intrinsic::dbg_value:
211             return LookupResult::Ignore;
212         }
213 
214         if (log && name)
215             log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
216     }
217     else
218     {
219         name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
220     }
221 
222     // Find the address of the function.
223 
224     clang::NamedDecl *fun_decl = DeclForGlobal (fun);
225 
226     if (fun_decl)
227     {
228         if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
229         {
230             std::vector<lldb_private::ConstString> alternates;
231             bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
232             if (!found_it)
233             {
234                 if (log)
235                     log->Printf("Address of function \"%s\" not found.\n", name.GetCString());
236                 // Check for an alternate mangling for names from the standard library.
237                 // For example, "std::basic_string<...>" has an alternate mangling scheme per
238                 // the Itanium C++ ABI.
239                 lldb::ProcessSP process_sp = m_data_allocator.GetTarget()->GetProcessSP();
240                 if (process_sp)
241                 {
242                     lldb_private::CPPLanguageRuntime *cpp_runtime = process_sp->GetCPPLanguageRuntime();
243                     if (cpp_runtime && cpp_runtime->GetAlternateManglings(name, alternates))
244                     {
245                         for (size_t i = 0; i < alternates.size(); ++i)
246                         {
247                             const lldb_private::ConstString &alternate_name = alternates[i];
248                             if (log)
249                                 log->Printf("Looking up address of function \"%s\" with alternate name \"%s\"",
250                                             name.GetCString(), alternate_name.GetCString());
251                             if ((found_it = m_decl_map->GetFunctionAddress (alternate_name, fun_addr)))
252                             {
253                                 if (log)
254                                     log->Printf("Found address of function \"%s\" with alternate name \"%s\"",
255                                                 name.GetCString(), alternate_name.GetCString());
256                                 break;
257                             }
258                         }
259                     }
260                 }
261             }
262 
263             if (!found_it)
264             {
265                 lldb_private::Mangled mangled_name(name);
266                 if (m_error_stream)
267                 {
268                     if (mangled_name.GetMangledName())
269                         m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
270                                                mangled_name.GetName(lldb::eLanguageTypeObjC_plus_plus).GetCString(),
271                                                mangled_name.GetMangledName().GetCString());
272                     else
273                         m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
274                                                mangled_name.GetName(lldb::eLanguageTypeObjC_plus_plus).GetCString());
275                 }
276                 return LookupResult::Fail;
277             }
278         }
279     }
280     else
281     {
282         if (!m_decl_map->GetFunctionAddress (name, fun_addr))
283         {
284             if (log)
285                 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
286 
287             if (m_error_stream)
288                 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
289 
290             return LookupResult::Fail;
291         }
292     }
293 
294     if (log)
295         log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
296 
297     return LookupResult::Success;
298 }
299 
300 llvm::Constant *
BuildFunctionPointer(llvm::Type * type,uint64_t ptr)301 IRForTarget::BuildFunctionPointer (llvm::Type *type,
302                                    uint64_t ptr)
303 {
304     PointerType *fun_ptr_ty = PointerType::getUnqual(type);
305     Constant *fun_addr_int = ConstantInt::get(m_intptr_ty, ptr, false);
306     return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
307 }
308 
309 void
RegisterFunctionMetadata(LLVMContext & context,llvm::Value * function_ptr,const char * name)310 IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
311                                       llvm::Value *function_ptr,
312                                       const char *name)
313 {
314     for (llvm::User *user : function_ptr->users())
315     {
316         if (Instruction *user_inst = dyn_cast<Instruction>(user))
317         {
318             MDString* md_name = MDString::get(context, StringRef(name));
319 
320             MDNode *metadata = MDNode::get(context, md_name);
321 
322             user_inst->setMetadata("lldb.call.realName", metadata);
323         }
324         else
325         {
326             RegisterFunctionMetadata (context, user, name);
327         }
328     }
329 }
330 
331 bool
ResolveFunctionPointers(llvm::Module & llvm_module)332 IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module)
333 {
334     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
335 
336     for (llvm::Module::iterator fi = llvm_module.begin();
337          fi != llvm_module.end();
338          ++fi)
339     {
340         Function *fun = fi;
341 
342         bool is_decl = fun->isDeclaration();
343 
344         if (log)
345             log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
346 
347         if (!is_decl)
348             continue;
349 
350         if (fun->use_empty())
351             continue; // ignore
352 
353         uint64_t addr = LLDB_INVALID_ADDRESS;
354         lldb_private::ConstString name;
355         Constant **value_ptr = NULL;
356 
357         LookupResult result = GetFunctionAddress(fun,
358                                                  addr,
359                                                  name,
360                                                  value_ptr);
361 
362         switch (result)
363         {
364         case LookupResult::Fail:
365             return false; // GetFunctionAddress reports its own errors
366 
367         case LookupResult::Ignore:
368             break; // Nothing to do
369 
370         case LookupResult::Success:
371             {
372                 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
373 
374                 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
375 
376                 if (value_ptr)
377                     *value_ptr = value;
378 
379                 // If we are replacing a function with the nobuiltin attribute, it may
380                 // be called with the builtin attribute on call sites. Remove any such
381                 // attributes since it's illegal to have a builtin call to something
382                 // other than a nobuiltin function.
383                 if (fun->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
384                     llvm::Attribute builtin = llvm::Attribute::get(fun->getContext(), llvm::Attribute::Builtin);
385 
386                     for (auto u : fun->users()) {
387                         if (auto call = dyn_cast<CallInst>(u)) {
388                             call->removeAttribute(AttributeSet::FunctionIndex, builtin);
389                         }
390                     }
391                 }
392 
393                 fun->replaceAllUsesWith(value);
394             }
395             break;
396         }
397     }
398 
399     return true;
400 }
401 
402 
403 clang::NamedDecl *
DeclForGlobal(const GlobalValue * global_val,Module * module)404 IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
405 {
406     NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
407 
408     if (!named_metadata)
409         return NULL;
410 
411     unsigned num_nodes = named_metadata->getNumOperands();
412     unsigned node_index;
413 
414     for (node_index = 0;
415          node_index < num_nodes;
416          ++node_index)
417     {
418         llvm::MDNode *metadata_node = dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index));
419         if (!metadata_node)
420             return NULL;
421 
422         if (metadata_node->getNumOperands() != 2)
423             continue;
424 
425         if (mdconst::dyn_extract_or_null<GlobalValue>(metadata_node->getOperand(0)) != global_val)
426             continue;
427 
428         ConstantInt *constant_int = mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1));
429 
430         if (!constant_int)
431             return NULL;
432 
433         uintptr_t ptr = constant_int->getZExtValue();
434 
435         return reinterpret_cast<clang::NamedDecl *>(ptr);
436     }
437 
438     return NULL;
439 }
440 
441 clang::NamedDecl *
DeclForGlobal(GlobalValue * global_val)442 IRForTarget::DeclForGlobal (GlobalValue *global_val)
443 {
444     return DeclForGlobal(global_val, m_module);
445 }
446 
447 bool
CreateResultVariable(llvm::Function & llvm_function)448 IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
449 {
450     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
451 
452     if (!m_resolve_vars)
453         return true;
454 
455     // Find the result variable.  If it doesn't exist, we can give up right here.
456 
457     ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
458 
459     std::string result_name_str;
460     const char *result_name = NULL;
461 
462     for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
463          vi != ve;
464          ++vi)
465     {
466         result_name_str = vi->first().str();
467         const char *value_name = result_name_str.c_str();
468 
469         if (strstr(value_name, "$__lldb_expr_result_ptr") &&
470             strncmp(value_name, "_ZGV", 4))
471         {
472             result_name = value_name;
473             m_result_is_pointer = true;
474             break;
475         }
476 
477         if (strstr(value_name, "$__lldb_expr_result") &&
478             strncmp(value_name, "_ZGV", 4))
479         {
480             result_name = value_name;
481             m_result_is_pointer = false;
482             break;
483         }
484     }
485 
486     if (!result_name)
487     {
488         if (log)
489             log->PutCString("Couldn't find result variable");
490 
491         return true;
492     }
493 
494     if (log)
495         log->Printf("Result name: \"%s\"", result_name);
496 
497     Value *result_value = m_module->getNamedValue(result_name);
498 
499     if (!result_value)
500     {
501         if (log)
502             log->PutCString("Result variable had no data");
503 
504         if (m_error_stream)
505             m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
506 
507         return false;
508     }
509 
510     if (log)
511         log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
512 
513     GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
514 
515     if (!result_global)
516     {
517         if (log)
518             log->PutCString("Result variable isn't a GlobalVariable");
519 
520         if (m_error_stream)
521             m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
522 
523         return false;
524     }
525 
526     clang::NamedDecl *result_decl = DeclForGlobal (result_global);
527     if (!result_decl)
528     {
529         if (log)
530             log->PutCString("Result variable doesn't have a corresponding Decl");
531 
532         if (m_error_stream)
533             m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
534 
535         return false;
536     }
537 
538     if (log)
539     {
540         std::string decl_desc_str;
541         raw_string_ostream decl_desc_stream(decl_desc_str);
542         result_decl->print(decl_desc_stream);
543         decl_desc_stream.flush();
544 
545         log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
546     }
547 
548     clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
549     if (!result_var)
550     {
551         if (log)
552             log->PutCString("Result variable Decl isn't a VarDecl");
553 
554         if (m_error_stream)
555             m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
556 
557         return false;
558     }
559 
560     // Get the next available result name from m_decl_map and create the persistent
561     // variable for it
562 
563     // If the result is an Lvalue, it is emitted as a pointer; see
564     // ASTResultSynthesizer::SynthesizeBodyResult.
565     if (m_result_is_pointer)
566     {
567         clang::QualType pointer_qual_type = result_var->getType();
568         const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
569 
570         const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
571         const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
572 
573         if (pointer_pointertype)
574         {
575             clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
576 
577             m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
578                                                          &result_decl->getASTContext());
579         }
580         else if (pointer_objcobjpointertype)
581         {
582             clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
583 
584             m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
585                                                          &result_decl->getASTContext());
586         }
587         else
588         {
589             if (log)
590                 log->PutCString("Expected result to have pointer type, but it did not");
591 
592             if (m_error_stream)
593                 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
594 
595             return false;
596         }
597     }
598     else
599     {
600         m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
601                                                      &result_decl->getASTContext());
602     }
603 
604 
605     lldb::TargetSP target_sp (m_data_allocator.GetTarget());
606     lldb_private::ExecutionContext exe_ctx (target_sp, true);
607     if (m_result_type.GetBitSize(exe_ctx.GetBestExecutionContextScope()) == 0)
608     {
609         lldb_private::StreamString type_desc_stream;
610         m_result_type.DumpTypeDescription(&type_desc_stream);
611 
612         if (log)
613             log->Printf("Result type has size 0");
614 
615         if (m_error_stream)
616             m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
617                                    type_desc_stream.GetData());
618         return false;
619     }
620 
621     if (log)
622     {
623         lldb_private::StreamString type_desc_stream;
624         m_result_type.DumpTypeDescription(&type_desc_stream);
625 
626         log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
627     }
628 
629     m_result_name = lldb_private::ConstString("$RESULT_NAME");
630 
631     if (log)
632         log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
633                     m_result_name.GetCString(),
634                     m_result_type.GetByteSize(nullptr));
635 
636     // Construct a new result global and set up its metadata
637 
638     GlobalVariable *new_result_global = new GlobalVariable((*m_module),
639                                                            result_global->getType()->getElementType(),
640                                                            false, /* not constant */
641                                                            GlobalValue::ExternalLinkage,
642                                                            NULL, /* no initializer */
643                                                            m_result_name.GetCString ());
644 
645     // It's too late in compilation to create a new VarDecl for this, but we don't
646     // need to.  We point the metadata at the old VarDecl.  This creates an odd
647     // anomaly: a variable with a Value whose name is something like $0 and a
648     // Decl whose name is $__lldb_expr_result.  This condition is handled in
649     // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
650     // fixed up.
651 
652     ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
653                                                      reinterpret_cast<uint64_t>(result_decl),
654                                                      false);
655 
656     llvm::Metadata *values[2];
657     values[0] = ConstantAsMetadata::get(new_result_global);
658     values[1] = ConstantAsMetadata::get(new_constant_int);
659 
660     ArrayRef<Metadata *> value_ref(values, 2);
661 
662     MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
663     NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
664     named_metadata->addOperand(persistent_global_md);
665 
666     if (log)
667         log->Printf("Replacing \"%s\" with \"%s\"",
668                     PrintValue(result_global).c_str(),
669                     PrintValue(new_result_global).c_str());
670 
671     if (result_global->use_empty())
672     {
673         // We need to synthesize a store for this variable, because otherwise
674         // there's nothing to put into its equivalent persistent variable.
675 
676         BasicBlock &entry_block(llvm_function.getEntryBlock());
677         Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
678 
679         if (!first_entry_instruction)
680             return false;
681 
682         if (!result_global->hasInitializer())
683         {
684             if (log)
685                 log->Printf("Couldn't find initializer for unused variable");
686 
687             if (m_error_stream)
688                 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
689 
690             return false;
691         }
692 
693         Constant *initializer = result_global->getInitializer();
694 
695         StoreInst *synthesized_store = new StoreInst(initializer,
696                                                      new_result_global,
697                                                      first_entry_instruction);
698 
699         if (log)
700             log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
701     }
702     else
703     {
704         result_global->replaceAllUsesWith(new_result_global);
705     }
706 
707     if (!m_decl_map->AddPersistentVariable(result_decl,
708                                            m_result_name,
709                                            m_result_type,
710                                            true,
711                                            m_result_is_pointer))
712         return false;
713 
714     result_global->eraseFromParent();
715 
716     return true;
717 }
718 
719 bool
RewriteObjCConstString(llvm::GlobalVariable * ns_str,llvm::GlobalVariable * cstr)720 IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
721                                      llvm::GlobalVariable *cstr)
722 {
723     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
724 
725     Type *ns_str_ty = ns_str->getType();
726 
727     Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
728     Type *i32_ty = Type::getInt32Ty(m_module->getContext());
729     Type *i8_ty = Type::getInt8Ty(m_module->getContext());
730 
731     if (!m_CFStringCreateWithBytes)
732     {
733         lldb::addr_t CFStringCreateWithBytes_addr;
734 
735         static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
736 
737         if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
738         {
739             if (log)
740                 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
741 
742             if (m_error_stream)
743                 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
744 
745             return false;
746         }
747 
748         if (log)
749             log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
750 
751         // Build the function type:
752         //
753         // CFStringRef CFStringCreateWithBytes (
754         //   CFAllocatorRef alloc,
755         //   const UInt8 *bytes,
756         //   CFIndex numBytes,
757         //   CFStringEncoding encoding,
758         //   Boolean isExternalRepresentation
759         // );
760         //
761         // We make the following substitutions:
762         //
763         // CFStringRef -> i8*
764         // CFAllocatorRef -> i8*
765         // UInt8 * -> i8*
766         // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
767         // CFStringEncoding -> i32
768         // Boolean -> i8
769 
770         Type *arg_type_array[5];
771 
772         arg_type_array[0] = i8_ptr_ty;
773         arg_type_array[1] = i8_ptr_ty;
774         arg_type_array[2] = m_intptr_ty;
775         arg_type_array[3] = i32_ty;
776         arg_type_array[4] = i8_ty;
777 
778         ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
779 
780         llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
781 
782         // Build the constant containing the pointer to the function
783         PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
784         Constant *CFSCWB_addr_int = ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
785         m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
786     }
787 
788     ConstantDataSequential *string_array = NULL;
789 
790     if (cstr)
791         string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
792 
793     Constant *alloc_arg         = Constant::getNullValue(i8_ptr_ty);
794     Constant *bytes_arg         = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
795     Constant *numBytes_arg      = ConstantInt::get(m_intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
796     Constant *encoding_arg      = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
797     Constant *isExternal_arg    = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
798 
799     Value *argument_array[5];
800 
801     argument_array[0] = alloc_arg;
802     argument_array[1] = bytes_arg;
803     argument_array[2] = numBytes_arg;
804     argument_array[3] = encoding_arg;
805     argument_array[4] = isExternal_arg;
806 
807     ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
808 
809     FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
810         return CallInst::Create(m_CFStringCreateWithBytes,
811                                 CFSCWB_arguments,
812                                 "CFStringCreateWithBytes",
813                                 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
814     });
815 
816     if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
817     {
818         if (log)
819             log->PutCString("Couldn't replace the NSString with the result of the call");
820 
821         if (m_error_stream)
822             m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
823 
824         return false;
825     }
826 
827     ns_str->eraseFromParent();
828 
829     return true;
830 }
831 
832 bool
RewriteObjCConstStrings()833 IRForTarget::RewriteObjCConstStrings()
834 {
835     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
836 
837     ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
838 
839     for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
840          vi != ve;
841          ++vi)
842     {
843         std::string value_name = vi->first().str();
844         const char *value_name_cstr = value_name.c_str();
845 
846         if (strstr(value_name_cstr, "_unnamed_cfstring_"))
847         {
848             Value *nsstring_value = vi->second;
849 
850             GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
851 
852             if (!nsstring_global)
853             {
854                 if (log)
855                     log->PutCString("NSString variable is not a GlobalVariable");
856 
857                 if (m_error_stream)
858                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
859 
860                 return false;
861             }
862 
863             if (!nsstring_global->hasInitializer())
864             {
865                 if (log)
866                     log->PutCString("NSString variable does not have an initializer");
867 
868                 if (m_error_stream)
869                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
870 
871                 return false;
872             }
873 
874             ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
875 
876             if (!nsstring_struct)
877             {
878                 if (log)
879                     log->PutCString("NSString variable's initializer is not a ConstantStruct");
880 
881                 if (m_error_stream)
882                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
883 
884                 return false;
885             }
886 
887             // We expect the following structure:
888             //
889             // struct {
890             //   int *isa;
891             //   int flags;
892             //   char *str;
893             //   long length;
894             // };
895 
896             if (nsstring_struct->getNumOperands() != 4)
897             {
898                 if (log)
899                     log->Printf("NSString variable's initializer structure has an unexpected number of members.  Should be 4, is %d", nsstring_struct->getNumOperands());
900 
901                 if (m_error_stream)
902                     m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
903 
904                 return false;
905             }
906 
907             Constant *nsstring_member = nsstring_struct->getOperand(2);
908 
909             if (!nsstring_member)
910             {
911                 if (log)
912                     log->PutCString("NSString initializer's str element was empty");
913 
914                 if (m_error_stream)
915                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
916 
917                 return false;
918             }
919 
920             ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
921 
922             if (!nsstring_expr)
923             {
924                 if (log)
925                     log->PutCString("NSString initializer's str element is not a ConstantExpr");
926 
927                 if (m_error_stream)
928                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
929 
930                 return false;
931             }
932 
933             if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
934             {
935                 if (log)
936                     log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
937 
938                 if (m_error_stream)
939                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
940 
941                 return false;
942             }
943 
944             Constant *nsstring_cstr = nsstring_expr->getOperand(0);
945 
946             GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
947 
948             if (!cstr_global)
949             {
950                 if (log)
951                     log->PutCString("NSString initializer's str element is not a GlobalVariable");
952 
953                 if (m_error_stream)
954                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
955 
956                 return false;
957             }
958 
959             if (!cstr_global->hasInitializer())
960             {
961                 if (log)
962                     log->PutCString("NSString initializer's str element does not have an initializer");
963 
964                 if (m_error_stream)
965                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
966 
967                 return false;
968             }
969 
970             /*
971             if (!cstr_array)
972             {
973                 if (log)
974                     log->PutCString("NSString initializer's str element is not a ConstantArray");
975 
976                 if (m_error_stream)
977                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
978 
979                 return false;
980             }
981 
982             if (!cstr_array->isCString())
983             {
984                 if (log)
985                     log->PutCString("NSString initializer's str element is not a C string array");
986 
987                 if (m_error_stream)
988                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
989 
990                 return false;
991             }
992             */
993 
994             ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
995 
996             if (log)
997             {
998                 if (cstr_array)
999                     log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().str().c_str());
1000                 else
1001                     log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
1002             }
1003 
1004             if (!cstr_array)
1005                 cstr_global = NULL;
1006 
1007             if (!RewriteObjCConstString(nsstring_global, cstr_global))
1008             {
1009                 if (log)
1010                     log->PutCString("Error rewriting the constant string");
1011 
1012                 // We don't print an error message here because RewriteObjCConstString has done so for us.
1013 
1014                 return false;
1015             }
1016         }
1017     }
1018 
1019     for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1020          vi != ve;
1021          ++vi)
1022     {
1023         std::string value_name = vi->first().str();
1024         const char *value_name_cstr = value_name.c_str();
1025 
1026         if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
1027         {
1028             GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1029 
1030             if (!gv)
1031             {
1032                 if (log)
1033                     log->PutCString("__CFConstantStringClassReference is not a global variable");
1034 
1035                 if (m_error_stream)
1036                     m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1037 
1038                 return false;
1039             }
1040 
1041             gv->eraseFromParent();
1042 
1043             break;
1044         }
1045     }
1046 
1047     return true;
1048 }
1049 
IsObjCSelectorRef(Value * value)1050 static bool IsObjCSelectorRef (Value *value)
1051 {
1052     GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
1053 
1054     if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("OBJC_SELECTOR_REFERENCES_"))
1055         return false;
1056 
1057     return true;
1058 }
1059 
1060 // This function does not report errors; its callers are responsible.
1061 bool
RewriteObjCSelector(Instruction * selector_load)1062 IRForTarget::RewriteObjCSelector (Instruction* selector_load)
1063 {
1064     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1065 
1066     LoadInst *load = dyn_cast<LoadInst>(selector_load);
1067 
1068     if (!load)
1069         return false;
1070 
1071     // Unpack the message name from the selector.  In LLVM IR, an objc_msgSend gets represented as
1072     //
1073     // %tmp     = load i8** @"OBJC_SELECTOR_REFERENCES_" ; <i8*>
1074     // %call    = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1075     //
1076     // where %obj is the object pointer and %tmp is the selector.
1077     //
1078     // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1079     // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
1080 
1081     // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1082 
1083     GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1084 
1085     if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1086         return false;
1087 
1088     Constant *osr_initializer = _objc_selector_references_->getInitializer();
1089 
1090     ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1091 
1092     if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1093         return false;
1094 
1095     Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1096 
1097     if (!osr_initializer_base)
1098         return false;
1099 
1100     // Find the string's initializer (a ConstantArray) and get the string from it
1101 
1102     GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1103 
1104     if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1105         return false;
1106 
1107     Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1108 
1109     ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
1110 
1111     if (!omvn_initializer_array->isString())
1112         return false;
1113 
1114     std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1115 
1116     if (log)
1117         log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
1118 
1119     // Construct a call to sel_registerName
1120 
1121     if (!m_sel_registerName)
1122     {
1123         lldb::addr_t sel_registerName_addr;
1124 
1125         static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
1126         if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
1127             return false;
1128 
1129         if (log)
1130             log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
1131 
1132         // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1133 
1134         // The below code would be "more correct," but in actuality what's required is uint8_t*
1135         //Type *sel_type = StructType::get(m_module->getContext());
1136         //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
1137         Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
1138 
1139         Type *type_array[1];
1140 
1141         type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1142 
1143         ArrayRef<Type *> srN_arg_types(type_array, 1);
1144 
1145         llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1146 
1147         // Build the constant containing the pointer to the function
1148         PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
1149         Constant *srN_addr_int = ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
1150         m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1151     }
1152 
1153     Value *argument_array[1];
1154 
1155     Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
1156 
1157     argument_array[0] = omvn_pointer;
1158 
1159     ArrayRef<Value *> srN_arguments(argument_array, 1);
1160 
1161     CallInst *srN_call = CallInst::Create(m_sel_registerName,
1162                                           srN_arguments,
1163                                           "sel_registerName",
1164                                           selector_load);
1165 
1166     // Replace the load with the call in all users
1167 
1168     selector_load->replaceAllUsesWith(srN_call);
1169 
1170     selector_load->eraseFromParent();
1171 
1172     return true;
1173 }
1174 
1175 bool
RewriteObjCSelectors(BasicBlock & basic_block)1176 IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
1177 {
1178     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1179 
1180     BasicBlock::iterator ii;
1181 
1182     typedef SmallVector <Instruction*, 2> InstrList;
1183     typedef InstrList::iterator InstrIterator;
1184 
1185     InstrList selector_loads;
1186 
1187     for (ii = basic_block.begin();
1188          ii != basic_block.end();
1189          ++ii)
1190     {
1191         Instruction &inst = *ii;
1192 
1193         if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1194             if (IsObjCSelectorRef(load->getPointerOperand()))
1195                 selector_loads.push_back(&inst);
1196     }
1197 
1198     InstrIterator iter;
1199 
1200     for (iter = selector_loads.begin();
1201          iter != selector_loads.end();
1202          ++iter)
1203     {
1204         if (!RewriteObjCSelector(*iter))
1205         {
1206             if (m_error_stream)
1207                 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1208 
1209             if (log)
1210                 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
1211 
1212             return false;
1213         }
1214     }
1215 
1216     return true;
1217 }
1218 
1219 // This function does not report errors; its callers are responsible.
1220 bool
RewritePersistentAlloc(llvm::Instruction * persistent_alloc)1221 IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
1222 {
1223     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1224 
1225     AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1226 
1227     MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1228 
1229     if (!alloc_md || !alloc_md->getNumOperands())
1230         return false;
1231 
1232     ConstantInt *constant_int = mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0));
1233 
1234     if (!constant_int)
1235         return false;
1236 
1237     // We attempt to register this as a new persistent variable with the DeclMap.
1238 
1239     uintptr_t ptr = constant_int->getZExtValue();
1240 
1241     clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
1242 
1243     lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1244                                                    &decl->getASTContext());
1245 
1246     StringRef decl_name (decl->getName());
1247     lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
1248     if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
1249         return false;
1250 
1251     GlobalVariable *persistent_global = new GlobalVariable((*m_module),
1252                                                            alloc->getType(),
1253                                                            false, /* not constant */
1254                                                            GlobalValue::ExternalLinkage,
1255                                                            NULL, /* no initializer */
1256                                                            alloc->getName().str().c_str());
1257 
1258     // What we're going to do here is make believe this was a regular old external
1259     // variable.  That means we need to make the metadata valid.
1260 
1261     NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
1262 
1263     llvm::Metadata *values[2];
1264     values[0] = ConstantAsMetadata::get(persistent_global);
1265     values[1] = ConstantAsMetadata::get(constant_int);
1266 
1267     ArrayRef<llvm::Metadata *> value_ref(values, 2);
1268 
1269     MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
1270     named_metadata->addOperand(persistent_global_md);
1271 
1272     // Now, since the variable is a pointer variable, we will drop in a load of that
1273     // pointer variable.
1274 
1275     LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1276 
1277     if (log)
1278         log->Printf("Replacing \"%s\" with \"%s\"",
1279                     PrintValue(alloc).c_str(),
1280                     PrintValue(persistent_load).c_str());
1281 
1282     alloc->replaceAllUsesWith(persistent_load);
1283     alloc->eraseFromParent();
1284 
1285     return true;
1286 }
1287 
1288 bool
RewritePersistentAllocs(llvm::BasicBlock & basic_block)1289 IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
1290 {
1291     if (!m_resolve_vars)
1292         return true;
1293 
1294     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1295 
1296     BasicBlock::iterator ii;
1297 
1298     typedef SmallVector <Instruction*, 2> InstrList;
1299     typedef InstrList::iterator InstrIterator;
1300 
1301     InstrList pvar_allocs;
1302 
1303     for (ii = basic_block.begin();
1304          ii != basic_block.end();
1305          ++ii)
1306     {
1307         Instruction &inst = *ii;
1308 
1309         if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
1310         {
1311             llvm::StringRef alloc_name = alloc->getName();
1312 
1313             if (alloc_name.startswith("$") &&
1314                 !alloc_name.startswith("$__lldb"))
1315             {
1316                 if (alloc_name.find_first_of("0123456789") == 1)
1317                 {
1318                     if (log)
1319                         log->Printf("Rejecting a numeric persistent variable.");
1320 
1321                     if (m_error_stream)
1322                         m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1323 
1324                     return false;
1325                 }
1326 
1327                 pvar_allocs.push_back(alloc);
1328             }
1329         }
1330     }
1331 
1332     InstrIterator iter;
1333 
1334     for (iter = pvar_allocs.begin();
1335          iter != pvar_allocs.end();
1336          ++iter)
1337     {
1338         if (!RewritePersistentAlloc(*iter))
1339         {
1340             if (m_error_stream)
1341                 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1342 
1343             if (log)
1344                 log->PutCString("Couldn't rewrite the creation of a persistent variable");
1345 
1346             return false;
1347         }
1348     }
1349 
1350     return true;
1351 }
1352 
1353 bool
MaterializeInitializer(uint8_t * data,Constant * initializer)1354 IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1355 {
1356     if (!initializer)
1357         return true;
1358 
1359     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1360 
1361     if (log && log->GetVerbose())
1362         log->Printf("  MaterializeInitializer(%p, %s)", (void *)data, PrintValue(initializer).c_str());
1363 
1364     Type *initializer_type = initializer->getType();
1365 
1366     if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1367     {
1368         memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1369         return true;
1370     }
1371     else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
1372     {
1373         if (array_initializer->isString())
1374         {
1375             std::string array_initializer_string = array_initializer->getAsString();
1376             memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1377         }
1378         else
1379         {
1380             ArrayType *array_initializer_type = array_initializer->getType();
1381             Type *array_element_type = array_initializer_type->getElementType();
1382 
1383             size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1384 
1385             for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
1386             {
1387                 Value *operand_value = array_initializer->getOperand(i);
1388                 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1389 
1390                 if (!operand_constant)
1391                     return false;
1392 
1393                 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
1394                     return false;
1395             }
1396         }
1397         return true;
1398     }
1399     else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1400     {
1401         StructType *struct_initializer_type = struct_initializer->getType();
1402         const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1403 
1404         for (unsigned i = 0;
1405              i < struct_initializer->getNumOperands();
1406              ++i)
1407         {
1408             if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1409                 return false;
1410         }
1411         return true;
1412     }
1413     else if (isa<ConstantAggregateZero>(initializer))
1414     {
1415         memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1416         return true;
1417     }
1418     return false;
1419 }
1420 
1421 bool
MaterializeInternalVariable(GlobalVariable * global_variable)1422 IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1423 {
1424     if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1425         return false;
1426 
1427     if (global_variable == m_reloc_placeholder)
1428         return true;
1429 
1430     uint64_t offset = m_data_allocator.GetStream().GetSize();
1431 
1432     llvm::Type *variable_type = global_variable->getType();
1433 
1434     Constant *initializer = global_variable->getInitializer();
1435 
1436     llvm::Type *initializer_type = initializer->getType();
1437 
1438     size_t size = m_target_data->getTypeAllocSize(initializer_type);
1439     size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1440 
1441     const size_t mask = (align - 1);
1442     uint64_t aligned_offset = (offset + mask) & ~mask;
1443     m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
1444     offset = aligned_offset;
1445 
1446     lldb_private::DataBufferHeap data(size, '\0');
1447 
1448     if (initializer)
1449         if (!MaterializeInitializer(data.GetBytes(), initializer))
1450             return false;
1451 
1452     m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
1453 
1454     Constant *new_pointer = BuildRelocation(variable_type, offset);
1455 
1456     global_variable->replaceAllUsesWith(new_pointer);
1457 
1458     global_variable->eraseFromParent();
1459 
1460     return true;
1461 }
1462 
1463 // This function does not report errors; its callers are responsible.
1464 bool
MaybeHandleVariable(Value * llvm_value_ptr)1465 IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
1466 {
1467     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1468 
1469     if (log)
1470         log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
1471 
1472     if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
1473     {
1474         switch (constant_expr->getOpcode())
1475         {
1476         default:
1477             break;
1478         case Instruction::GetElementPtr:
1479         case Instruction::BitCast:
1480             Value *s = constant_expr->getOperand(0);
1481             if (!MaybeHandleVariable(s))
1482                 return false;
1483         }
1484     }
1485     else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
1486     {
1487         if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1488             return MaterializeInternalVariable(global_variable);
1489 
1490         clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1491 
1492         if (!named_decl)
1493         {
1494             if (IsObjCSelectorRef(llvm_value_ptr))
1495                 return true;
1496 
1497             if (!global_variable->hasExternalLinkage())
1498                 return true;
1499 
1500             if (log)
1501                 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
1502 
1503             return false;
1504         }
1505 
1506         std::string name (named_decl->getName().str());
1507 
1508         clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1509         if (value_decl == NULL)
1510             return false;
1511 
1512         lldb_private::ClangASTType clang_type(&value_decl->getASTContext(), value_decl->getType());
1513 
1514         const Type *value_type = NULL;
1515 
1516         if (name[0] == '$')
1517         {
1518             // The $__lldb_expr_result name indicates the return value has allocated as
1519             // a static variable.  Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1520             // accesses to this static variable need to be redirected to the result of dereferencing
1521             // a pointer that is passed in as one of the arguments.
1522             //
1523             // Consequently, when reporting the size of the type, we report a pointer type pointing
1524             // to the type of $__lldb_expr_result, not the type itself.
1525             //
1526             // We also do this for any user-declared persistent variables.
1527             clang_type = clang_type.GetPointerType();
1528             value_type = PointerType::get(global_variable->getType(), 0);
1529         }
1530         else
1531         {
1532             value_type = global_variable->getType();
1533         }
1534 
1535         const uint64_t value_size = clang_type.GetByteSize(nullptr);
1536         lldb::offset_t value_alignment = (clang_type.GetTypeBitAlign() + 7ull) / 8ull;
1537 
1538         if (log)
1539         {
1540             log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRIu64 "]",
1541                         name.c_str(),
1542                         clang_type.GetQualType().getAsString().c_str(),
1543                         PrintType(value_type).c_str(),
1544                         value_size,
1545                         value_alignment);
1546         }
1547 
1548 
1549         if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
1550                                                         lldb_private::ConstString (name.c_str()),
1551                                                         llvm_value_ptr,
1552                                                         value_size,
1553                                                         value_alignment))
1554         {
1555             if (!global_variable->hasExternalLinkage())
1556                 return true;
1557             else if (HandleSymbol (global_variable))
1558                 return true;
1559             else
1560                 return false;
1561         }
1562     }
1563     else if (dyn_cast<llvm::Function>(llvm_value_ptr))
1564     {
1565         if (log)
1566             log->Printf("Function pointers aren't handled right now");
1567 
1568         return false;
1569     }
1570 
1571     return true;
1572 }
1573 
1574 // This function does not report errors; its callers are responsible.
1575 bool
HandleSymbol(Value * symbol)1576 IRForTarget::HandleSymbol (Value *symbol)
1577 {
1578     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1579 
1580     lldb_private::ConstString name(symbol->getName().str().c_str());
1581 
1582     lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
1583 
1584     if (symbol_addr == LLDB_INVALID_ADDRESS)
1585     {
1586         if (log)
1587             log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1588 
1589         return false;
1590     }
1591 
1592     if (log)
1593         log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
1594 
1595     Type *symbol_type = symbol->getType();
1596 
1597     Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
1598 
1599     Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1600 
1601     if (log)
1602         log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1603 
1604     symbol->replaceAllUsesWith(symbol_addr_ptr);
1605 
1606     return true;
1607 }
1608 
1609 bool
MaybeHandleCallArguments(CallInst * Old)1610 IRForTarget::MaybeHandleCallArguments (CallInst *Old)
1611 {
1612     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1613 
1614     if (log)
1615         log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
1616 
1617     for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
1618          op_index < num_ops;
1619          ++op_index)
1620         if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
1621         {
1622             if (m_error_stream)
1623                 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1624 
1625             return false;
1626         }
1627 
1628     return true;
1629 }
1630 
1631 bool
HandleObjCClass(Value * classlist_reference)1632 IRForTarget::HandleObjCClass(Value *classlist_reference)
1633 {
1634     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1635 
1636     GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1637 
1638     if (!global_variable)
1639         return false;
1640 
1641     Constant *initializer = global_variable->getInitializer();
1642 
1643     if (!initializer)
1644         return false;
1645 
1646     if (!initializer->hasName())
1647         return false;
1648 
1649     StringRef name(initializer->getName());
1650     lldb_private::ConstString name_cstr(name.str().c_str());
1651     lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1652 
1653     if (log)
1654         log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1655 
1656     if (class_ptr == LLDB_INVALID_ADDRESS)
1657         return false;
1658 
1659     if (global_variable->use_empty())
1660         return false;
1661 
1662     SmallVector<LoadInst *, 2> load_instructions;
1663 
1664     for (llvm::User *u : global_variable->users())
1665     {
1666         if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1667             load_instructions.push_back(load_instruction);
1668     }
1669 
1670     if (load_instructions.empty())
1671         return false;
1672 
1673     Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
1674 
1675     for (LoadInst *load_instruction : load_instructions)
1676     {
1677         Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1678 
1679         load_instruction->replaceAllUsesWith(class_bitcast);
1680 
1681         load_instruction->eraseFromParent();
1682     }
1683 
1684     return true;
1685 }
1686 
1687 bool
RemoveCXAAtExit(BasicBlock & basic_block)1688 IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1689 {
1690     BasicBlock::iterator ii;
1691 
1692     std::vector<CallInst *> calls_to_remove;
1693 
1694     for (ii = basic_block.begin();
1695          ii != basic_block.end();
1696          ++ii)
1697     {
1698         Instruction &inst = *ii;
1699 
1700         CallInst *call = dyn_cast<CallInst>(&inst);
1701 
1702         // MaybeHandleCallArguments handles error reporting; we are silent here
1703         if (!call)
1704             continue;
1705 
1706         bool remove = false;
1707 
1708         llvm::Function *func = call->getCalledFunction();
1709 
1710         if (func && func->getName() == "__cxa_atexit")
1711             remove = true;
1712 
1713         llvm::Value *val = call->getCalledValue();
1714 
1715         if (val && val->getName() == "__cxa_atexit")
1716             remove = true;
1717 
1718         if (remove)
1719             calls_to_remove.push_back(call);
1720     }
1721 
1722     for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1723          ci != ce;
1724          ++ci)
1725     {
1726         (*ci)->eraseFromParent();
1727     }
1728 
1729     return true;
1730 }
1731 
1732 bool
ResolveCalls(BasicBlock & basic_block)1733 IRForTarget::ResolveCalls(BasicBlock &basic_block)
1734 {
1735     /////////////////////////////////////////////////////////////////////////
1736     // Prepare the current basic block for execution in the remote process
1737     //
1738 
1739     BasicBlock::iterator ii;
1740 
1741     for (ii = basic_block.begin();
1742          ii != basic_block.end();
1743          ++ii)
1744     {
1745         Instruction &inst = *ii;
1746 
1747         CallInst *call = dyn_cast<CallInst>(&inst);
1748 
1749         // MaybeHandleCallArguments handles error reporting; we are silent here
1750         if (call && !MaybeHandleCallArguments(call))
1751             return false;
1752     }
1753 
1754     return true;
1755 }
1756 
1757 bool
ResolveExternals(Function & llvm_function)1758 IRForTarget::ResolveExternals (Function &llvm_function)
1759 {
1760     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1761 
1762     for (GlobalVariable &global_var : m_module->globals())
1763     {
1764         std::string global_name = global_var.getName().str();
1765 
1766         if (log)
1767             log->Printf("Examining %s, DeclForGlobalValue returns %p",
1768                         global_name.c_str(),
1769                         static_cast<void*>(DeclForGlobal(&global_var)));
1770 
1771         if (global_name.find("OBJC_IVAR") == 0)
1772         {
1773             if (!HandleSymbol(&global_var))
1774             {
1775                 if (m_error_stream)
1776                     m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", global_name.c_str());
1777 
1778                 return false;
1779             }
1780         }
1781         else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1782         {
1783             if (!HandleObjCClass(&global_var))
1784             {
1785                 if (m_error_stream)
1786                     m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1787 
1788                 return false;
1789             }
1790         }
1791         else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1792         {
1793             if (!HandleObjCClass(&global_var))
1794             {
1795                 if (m_error_stream)
1796                     m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1797 
1798                 return false;
1799             }
1800         }
1801         else if (DeclForGlobal(&global_var))
1802         {
1803             if (!MaybeHandleVariable (&global_var))
1804             {
1805                 if (m_error_stream)
1806                     m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", global_name.c_str());
1807 
1808                 return false;
1809             }
1810         }
1811     }
1812 
1813     return true;
1814 }
1815 
1816 bool
ReplaceStrings()1817 IRForTarget::ReplaceStrings ()
1818 {
1819     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1820 
1821     typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1822 
1823     OffsetsTy offsets;
1824 
1825     for (GlobalVariable &gv : m_module->globals())
1826     {
1827         if (!gv.hasInitializer())
1828             continue;
1829 
1830         Constant *gc = gv.getInitializer();
1831 
1832         std::string str;
1833 
1834         if (gc->isNullValue())
1835         {
1836             Type *gc_type = gc->getType();
1837 
1838             ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1839 
1840             if (!gc_array_type)
1841                 continue;
1842 
1843             Type *gc_element_type = gc_array_type->getElementType();
1844 
1845             IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1846 
1847             if (gc_integer_type->getBitWidth() != 8)
1848                 continue;
1849 
1850             str = "";
1851         }
1852         else
1853         {
1854             ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
1855 
1856             if (!gc_array)
1857                 continue;
1858 
1859             if (!gc_array->isCString())
1860                 continue;
1861 
1862             if (log)
1863                 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
1864 
1865             str = gc_array->getAsString();
1866         }
1867 
1868         offsets[&gv] = m_data_allocator.GetStream().GetSize();
1869 
1870         m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
1871     }
1872 
1873     Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
1874 
1875     for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1876          oi != oe;
1877          ++oi)
1878     {
1879         GlobalVariable *gv = oi->first;
1880         size_t offset = oi->second;
1881 
1882         Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1883 
1884         if (log)
1885             log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1886 
1887         for (llvm::User *u : gv->users())
1888         {
1889             if (log)
1890                 log->Printf("Found use %s", PrintValue(u).c_str());
1891 
1892             ConstantExpr *const_expr = dyn_cast<ConstantExpr>(u);
1893             StoreInst *store_inst = dyn_cast<StoreInst>(u);
1894 
1895             if (const_expr)
1896             {
1897                 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1898                 {
1899                     if (log)
1900                         log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1901 
1902                     return false;
1903                 }
1904 
1905                 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1906                 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1907 
1908                 const_expr->replaceAllUsesWith(new_gep);
1909             }
1910             else if (store_inst)
1911             {
1912                 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1913 
1914                 store_inst->setOperand(0, bit_cast);
1915             }
1916             else
1917             {
1918                 if (log)
1919                     log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1920 
1921                 return false;
1922             }
1923         }
1924 
1925         gv->eraseFromParent();
1926     }
1927 
1928     return true;
1929 }
1930 
1931 bool
ReplaceStaticLiterals(llvm::BasicBlock & basic_block)1932 IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1933 {
1934     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1935 
1936     typedef SmallVector <Value*, 2> ConstantList;
1937     typedef SmallVector <llvm::Instruction*, 2> UserList;
1938     typedef ConstantList::iterator ConstantIterator;
1939     typedef UserList::iterator UserIterator;
1940 
1941     ConstantList static_constants;
1942     UserList static_users;
1943 
1944     for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1945          ii != ie;
1946          ++ii)
1947     {
1948         llvm::Instruction &inst = *ii;
1949 
1950         for (Value *operand_val : inst.operand_values())
1951         {
1952             ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1953 
1954             if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
1955             {
1956                 static_constants.push_back(operand_val);
1957                 static_users.push_back(ii);
1958             }
1959         }
1960     }
1961 
1962     ConstantIterator constant_iter;
1963     UserIterator user_iter;
1964 
1965     for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1966          constant_iter != static_constants.end();
1967          ++constant_iter, ++user_iter)
1968     {
1969         Value *operand_val = *constant_iter;
1970         llvm::Instruction *inst = *user_iter;
1971 
1972         ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1973 
1974         if (operand_constant_fp)
1975         {
1976             Type *operand_type = operand_constant_fp->getType();
1977 
1978             APFloat operand_apfloat = operand_constant_fp->getValueAPF();
1979             APInt operand_apint = operand_apfloat.bitcastToAPInt();
1980 
1981             const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
1982             size_t operand_data_size = operand_apint.getBitWidth() / 8;
1983 
1984             if (log)
1985             {
1986                 std::string s;
1987                 raw_string_ostream ss(s);
1988                 for (size_t index = 0;
1989                      index < operand_data_size;
1990                      ++index)
1991                 {
1992                     ss << (uint32_t)operand_raw_data[index];
1993                     ss << " ";
1994                 }
1995                 ss.flush();
1996 
1997                 log->Printf("Found ConstantFP with size %" PRIu64 " and raw data %s", (uint64_t)operand_data_size, s.c_str());
1998             }
1999 
2000             lldb_private::DataBufferHeap data(operand_data_size, 0);
2001 
2002             if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
2003             {
2004                 uint8_t *data_bytes = data.GetBytes();
2005 
2006                 for (size_t index = 0;
2007                      index < operand_data_size;
2008                      ++index)
2009                 {
2010                     data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2011                 }
2012             }
2013             else
2014             {
2015                 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2016             }
2017 
2018             uint64_t offset = m_data_allocator.GetStream().GetSize();
2019 
2020             size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2021 
2022             const size_t mask = (align - 1);
2023             uint64_t aligned_offset = (offset + mask) & ~mask;
2024             m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
2025 
2026             m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
2027 
2028             llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
2029 
2030             Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
2031 
2032             llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2033 
2034             operand_constant_fp->replaceAllUsesWith(fp_load);
2035         }
2036     }
2037 
2038     return true;
2039 }
2040 
isGuardVariableRef(Value * V)2041 static bool isGuardVariableRef(Value *V)
2042 {
2043     Constant *Old = NULL;
2044 
2045     if (!(Old = dyn_cast<Constant>(V)))
2046         return false;
2047 
2048     ConstantExpr *CE = NULL;
2049 
2050     if ((CE = dyn_cast<ConstantExpr>(V)))
2051     {
2052         if (CE->getOpcode() != Instruction::BitCast)
2053             return false;
2054 
2055         Old = CE->getOperand(0);
2056     }
2057 
2058     GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
2059 
2060     if (!GV || !GV->hasName() ||
2061         (!GV->getName().startswith("_ZGV") && // Itanium ABI guard variable
2062          !GV->getName().endswith("@4IA")))    // Microsoft ABI guard variable
2063     {
2064         return false;
2065     }
2066 
2067     return true;
2068 }
2069 
2070 void
TurnGuardLoadIntoZero(llvm::Instruction * guard_load)2071 IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
2072 {
2073     Constant *zero(Constant::getNullValue(guard_load->getType()));
2074     guard_load->replaceAllUsesWith(zero);
2075     guard_load->eraseFromParent();
2076 }
2077 
ExciseGuardStore(Instruction * guard_store)2078 static void ExciseGuardStore(Instruction* guard_store)
2079 {
2080     guard_store->eraseFromParent();
2081 }
2082 
2083 bool
RemoveGuards(BasicBlock & basic_block)2084 IRForTarget::RemoveGuards(BasicBlock &basic_block)
2085 {
2086     ///////////////////////////////////////////////////////
2087     // Eliminate any reference to guard variables found.
2088     //
2089 
2090     BasicBlock::iterator ii;
2091 
2092     typedef SmallVector <Instruction*, 2> InstrList;
2093     typedef InstrList::iterator InstrIterator;
2094 
2095     InstrList guard_loads;
2096     InstrList guard_stores;
2097 
2098     for (ii = basic_block.begin();
2099          ii != basic_block.end();
2100          ++ii)
2101     {
2102         Instruction &inst = *ii;
2103 
2104         if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2105             if (isGuardVariableRef(load->getPointerOperand()))
2106                 guard_loads.push_back(&inst);
2107 
2108         if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2109             if (isGuardVariableRef(store->getPointerOperand()))
2110                 guard_stores.push_back(&inst);
2111     }
2112 
2113     InstrIterator iter;
2114 
2115     for (iter = guard_loads.begin();
2116          iter != guard_loads.end();
2117          ++iter)
2118         TurnGuardLoadIntoZero(*iter);
2119 
2120     for (iter = guard_stores.begin();
2121          iter != guard_stores.end();
2122          ++iter)
2123         ExciseGuardStore(*iter);
2124 
2125     return true;
2126 }
2127 
2128 // This function does not report errors; its callers are responsible.
2129 bool
UnfoldConstant(Constant * old_constant,FunctionValueCache & value_maker,FunctionValueCache & entry_instruction_finder)2130 IRForTarget::UnfoldConstant(Constant *old_constant,
2131                             FunctionValueCache &value_maker,
2132                             FunctionValueCache &entry_instruction_finder)
2133 {
2134     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2135 
2136     SmallVector<User*, 16> users;
2137 
2138     // We do this because the use list might change, invalidating our iterator.
2139     // Much better to keep a work list ourselves.
2140     for (llvm::User *u : old_constant->users())
2141         users.push_back(u);
2142 
2143     for (size_t i = 0;
2144          i < users.size();
2145          ++i)
2146     {
2147         User *user = users[i];
2148 
2149         if (Constant *constant = dyn_cast<Constant>(user))
2150         {
2151             // synthesize a new non-constant equivalent of the constant
2152 
2153             if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2154             {
2155                 switch (constant_expr->getOpcode())
2156                 {
2157                 default:
2158                     if (log)
2159                         log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
2160                     return false;
2161                 case Instruction::BitCast:
2162                     {
2163                         FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2164                             // UnaryExpr
2165                             //   OperandList[0] is value
2166 
2167                             if (constant_expr->getOperand(0) != old_constant)
2168                                 return constant_expr;
2169 
2170                             return new BitCastInst(value_maker.GetValue(function),
2171                                                    constant_expr->getType(),
2172                                                    "",
2173                                                    llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2174                         });
2175 
2176                         if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder))
2177                             return false;
2178                     }
2179                     break;
2180                 case Instruction::GetElementPtr:
2181                     {
2182                         // GetElementPtrConstantExpr
2183                         //   OperandList[0] is base
2184                         //   OperandList[1]... are indices
2185 
2186                         FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2187                             Value *ptr = constant_expr->getOperand(0);
2188 
2189                             if (ptr == old_constant)
2190                                 ptr = value_maker.GetValue(function);
2191 
2192                             std::vector<Value*> index_vector;
2193 
2194                             unsigned operand_index;
2195                             unsigned num_operands = constant_expr->getNumOperands();
2196 
2197                             for (operand_index = 1;
2198                                  operand_index < num_operands;
2199                                  ++operand_index)
2200                             {
2201                                 Value *operand = constant_expr->getOperand(operand_index);
2202 
2203                                 if (operand == old_constant)
2204                                     operand = value_maker.GetValue(function);
2205 
2206                                 index_vector.push_back(operand);
2207                             }
2208 
2209                             ArrayRef <Value*> indices(index_vector);
2210 
2211                             return GetElementPtrInst::Create(nullptr, ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2212                         });
2213 
2214                         if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder))
2215                             return false;
2216                     }
2217                     break;
2218                 }
2219             }
2220             else
2221             {
2222                 if (log)
2223                     log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
2224                 return false;
2225             }
2226         }
2227         else
2228         {
2229             if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
2230             {
2231                 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
2232             }
2233             else
2234             {
2235                 if (log)
2236                     log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
2237                 return false;
2238             }
2239         }
2240     }
2241 
2242     if (!isa<GlobalValue>(old_constant))
2243     {
2244         old_constant->destroyConstant();
2245     }
2246 
2247     return true;
2248 }
2249 
2250 bool
ReplaceVariables(Function & llvm_function)2251 IRForTarget::ReplaceVariables (Function &llvm_function)
2252 {
2253     if (!m_resolve_vars)
2254         return true;
2255 
2256     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2257 
2258     m_decl_map->DoStructLayout();
2259 
2260     if (log)
2261         log->Printf("Element arrangement:");
2262 
2263     uint32_t num_elements;
2264     uint32_t element_index;
2265 
2266     size_t size;
2267     lldb::offset_t alignment;
2268 
2269     if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2270         return false;
2271 
2272     Function::arg_iterator iter(llvm_function.getArgumentList().begin());
2273 
2274     if (iter == llvm_function.getArgumentList().end())
2275     {
2276         if (m_error_stream)
2277             m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2278 
2279         return false;
2280     }
2281 
2282     Argument *argument = iter;
2283 
2284     if (argument->getName().equals("this"))
2285     {
2286         ++iter;
2287 
2288         if (iter == llvm_function.getArgumentList().end())
2289         {
2290             if (m_error_stream)
2291                 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2292 
2293             return false;
2294         }
2295 
2296         argument = iter;
2297     }
2298     else if (argument->getName().equals("self"))
2299     {
2300         ++iter;
2301 
2302         if (iter == llvm_function.getArgumentList().end())
2303         {
2304             if (m_error_stream)
2305                 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2306 
2307             return false;
2308         }
2309 
2310         if (!iter->getName().equals("_cmd"))
2311         {
2312             if (m_error_stream)
2313                 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2314 
2315             return false;
2316         }
2317 
2318         ++iter;
2319 
2320         if (iter == llvm_function.getArgumentList().end())
2321         {
2322             if (m_error_stream)
2323                 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2324 
2325             return false;
2326         }
2327 
2328         argument = iter;
2329     }
2330 
2331     if (!argument->getName().equals("$__lldb_arg"))
2332     {
2333         if (m_error_stream)
2334             m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2335 
2336         return false;
2337     }
2338 
2339     if (log)
2340         log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
2341 
2342     BasicBlock &entry_block(llvm_function.getEntryBlock());
2343     Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
2344 
2345     if (!FirstEntryInstruction)
2346     {
2347         if (m_error_stream)
2348             m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2349 
2350         return false;
2351     }
2352 
2353     LLVMContext &context(m_module->getContext());
2354     IntegerType *offset_type(Type::getInt32Ty(context));
2355 
2356     if (!offset_type)
2357     {
2358         if (m_error_stream)
2359             m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2360 
2361         return false;
2362     }
2363 
2364     for (element_index = 0; element_index < num_elements; ++element_index)
2365     {
2366         const clang::NamedDecl *decl = NULL;
2367         Value *value = NULL;
2368         lldb::offset_t offset;
2369         lldb_private::ConstString name;
2370 
2371         if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
2372         {
2373             if (m_error_stream)
2374                 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2375 
2376             return false;
2377         }
2378 
2379         if (log)
2380             log->Printf("  \"%s\" (\"%s\") placed at %" PRIu64,
2381                         name.GetCString(),
2382                         decl->getNameAsString().c_str(),
2383                         offset);
2384 
2385         if (value)
2386         {
2387             if (log)
2388                 log->Printf("    Replacing [%s]", PrintValue(value).c_str());
2389 
2390             FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
2391                 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2392                 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2393                 // entry in order to produce the static variable that the AST thinks it is accessing.
2394 
2395                 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
2396 
2397                 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
2398                 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(nullptr,
2399                                                                                argument,
2400                                                                                offset_int,
2401                                                                                "",
2402                                                                                entry_instruction);
2403 
2404                 if (name == m_result_name && !m_result_is_pointer)
2405                 {
2406                     BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
2407                                                             value->getType()->getPointerTo(),
2408                                                             "",
2409                                                             entry_instruction);
2410 
2411                     LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
2412 
2413                     return load;
2414                 }
2415                 else
2416                 {
2417                     BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
2418 
2419                     return bit_cast;
2420                 }
2421             });
2422 
2423             if (Constant *constant = dyn_cast<Constant>(value))
2424             {
2425                 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
2426             }
2427             else if (Instruction *instruction = dyn_cast<Instruction>(value))
2428             {
2429                 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
2430             }
2431             else
2432             {
2433                 if (log)
2434                     log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
2435                 return false;
2436             }
2437 
2438             if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2439                 var->eraseFromParent();
2440         }
2441     }
2442 
2443     if (log)
2444         log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]", (int64_t)alignment, (uint64_t)size);
2445 
2446     return true;
2447 }
2448 
2449 llvm::Constant *
BuildRelocation(llvm::Type * type,uint64_t offset)2450 IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
2451 {
2452     llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset);
2453 
2454     llvm::Constant *offset_array[1];
2455 
2456     offset_array[0] = offset_int;
2457 
2458     llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2459     llvm::Type *char_type = llvm::Type::getInt8Ty(m_module->getContext());
2460     llvm::Type *char_pointer_type = char_type->getPointerTo();
2461 
2462     llvm::Constant *reloc_placeholder_bitcast = ConstantExpr::getBitCast(m_reloc_placeholder, char_pointer_type);
2463     llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(char_type, reloc_placeholder_bitcast, offsets);
2464     llvm::Constant *reloc_bitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2465 
2466     return reloc_bitcast;
2467 }
2468 
2469 bool
CompleteDataAllocation()2470 IRForTarget::CompleteDataAllocation ()
2471 {
2472     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2473 
2474     if (!m_data_allocator.GetStream().GetSize())
2475         return true;
2476 
2477     lldb::addr_t allocation = m_data_allocator.Allocate();
2478 
2479     if (log)
2480     {
2481         if (allocation)
2482             log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2483         else
2484             log->Printf("Failed to allocate static data");
2485     }
2486 
2487     if (!allocation || allocation == LLDB_INVALID_ADDRESS)
2488         return false;
2489 
2490     Constant *relocated_addr = ConstantInt::get(m_intptr_ty, (uint64_t)allocation);
2491     Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2492 
2493     m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2494 
2495     m_reloc_placeholder->eraseFromParent();
2496 
2497     return true;
2498 }
2499 
2500 bool
StripAllGVs(Module & llvm_module)2501 IRForTarget::StripAllGVs (Module &llvm_module)
2502 {
2503     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2504     std::vector<GlobalVariable *> global_vars;
2505     std::set<GlobalVariable *>erased_vars;
2506 
2507     bool erased = true;
2508 
2509     while (erased)
2510     {
2511         erased = false;
2512 
2513         for (GlobalVariable &global_var : llvm_module.globals())
2514         {
2515             global_var.removeDeadConstantUsers();
2516 
2517             if (global_var.use_empty())
2518             {
2519                 if (log)
2520                     log->Printf("Did remove %s",
2521                                 PrintValue(&global_var).c_str());
2522                 global_var.eraseFromParent();
2523                 erased = true;
2524                 break;
2525             }
2526         }
2527     }
2528 
2529     for (GlobalVariable &global_var : llvm_module.globals())
2530     {
2531         GlobalValue::user_iterator ui = global_var.user_begin();
2532 
2533         if (log)
2534             log->Printf("Couldn't remove %s because of %s",
2535                         PrintValue(&global_var).c_str(),
2536                         PrintValue(*ui).c_str());
2537     }
2538 
2539     return true;
2540 }
2541 
2542 bool
runOnModule(Module & llvm_module)2543 IRForTarget::runOnModule (Module &llvm_module)
2544 {
2545     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2546 
2547     m_module = &llvm_module;
2548     m_target_data.reset(new DataLayout(m_module));
2549     m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(), m_target_data->getPointerSizeInBits());
2550 
2551     if (log)
2552     {
2553         std::string s;
2554         raw_string_ostream oss(s);
2555 
2556         m_module->print(oss, NULL);
2557 
2558         oss.flush();
2559 
2560         log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2561     }
2562 
2563     Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str()));
2564 
2565     if (!main_function)
2566     {
2567         if (log)
2568             log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
2569 
2570         if (m_error_stream)
2571             m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
2572 
2573         return false;
2574     }
2575 
2576     if (!FixFunctionLinkage (*main_function))
2577     {
2578         if (log)
2579             log->Printf("Couldn't fix the linkage for the function");
2580 
2581         return false;
2582     }
2583 
2584     llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext());
2585 
2586     m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2587                                                    int8_ty,
2588                                                    false /* IsConstant */,
2589                                                    GlobalVariable::InternalLinkage,
2590                                                    Constant::getNullValue(int8_ty),
2591                                                    "reloc_placeholder",
2592                                                    NULL /* InsertBefore */,
2593                                                    GlobalVariable::NotThreadLocal /* ThreadLocal */,
2594                                                    0 /* AddressSpace */);
2595 
2596     ////////////////////////////////////////////////////////////
2597     // Replace $__lldb_expr_result with a persistent variable
2598     //
2599 
2600     if (!CreateResultVariable(*main_function))
2601     {
2602         if (log)
2603             log->Printf("CreateResultVariable() failed");
2604 
2605         // CreateResultVariable() reports its own errors, so we don't do so here
2606 
2607         return false;
2608     }
2609 
2610     if (log && log->GetVerbose())
2611     {
2612         std::string s;
2613         raw_string_ostream oss(s);
2614 
2615         m_module->print(oss, NULL);
2616 
2617         oss.flush();
2618 
2619         log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2620     }
2621 
2622     for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2623          fi != fe;
2624          ++fi)
2625     {
2626         llvm::Function *function = fi;
2627 
2628         if (function->begin() == function->end())
2629             continue;
2630 
2631         Function::iterator bbi;
2632 
2633         for (bbi = function->begin();
2634              bbi != function->end();
2635              ++bbi)
2636         {
2637             if (!RemoveGuards(*bbi))
2638             {
2639                 if (log)
2640                     log->Printf("RemoveGuards() failed");
2641 
2642                 // RemoveGuards() reports its own errors, so we don't do so here
2643 
2644                 return false;
2645             }
2646 
2647             if (!RewritePersistentAllocs(*bbi))
2648             {
2649                 if (log)
2650                     log->Printf("RewritePersistentAllocs() failed");
2651 
2652                 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2653 
2654                 return false;
2655             }
2656 
2657             if (!RemoveCXAAtExit(*bbi))
2658             {
2659                 if (log)
2660                     log->Printf("RemoveCXAAtExit() failed");
2661 
2662                 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2663 
2664                 return false;
2665             }
2666         }
2667     }
2668 
2669     ///////////////////////////////////////////////////////////////////////////////
2670     // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2671     //
2672 
2673     if (!RewriteObjCConstStrings())
2674     {
2675         if (log)
2676             log->Printf("RewriteObjCConstStrings() failed");
2677 
2678         // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2679 
2680         return false;
2681     }
2682 
2683     ///////////////////////////////
2684     // Resolve function pointers
2685     //
2686 
2687     if (!ResolveFunctionPointers(llvm_module))
2688     {
2689         if (log)
2690             log->Printf("ResolveFunctionPointers() failed");
2691 
2692         // ResolveFunctionPointers() reports its own errors, so we don't do so here
2693 
2694         return false;
2695     }
2696 
2697     for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2698          fi != fe;
2699          ++fi)
2700     {
2701         llvm::Function *function = fi;
2702 
2703         for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2704              bbi != bbe;
2705              ++bbi)
2706         {
2707             if (!RewriteObjCSelectors(*bbi))
2708             {
2709                 if (log)
2710                     log->Printf("RewriteObjCSelectors() failed");
2711 
2712                 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2713 
2714                 return false;
2715             }
2716         }
2717     }
2718 
2719     for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2720          fi != fe;
2721          ++fi)
2722     {
2723         llvm::Function *function = fi;
2724 
2725         for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2726              bbi != bbe;
2727              ++bbi)
2728         {
2729             if (!ResolveCalls(*bbi))
2730             {
2731                 if (log)
2732                     log->Printf("ResolveCalls() failed");
2733 
2734                 // ResolveCalls() reports its own errors, so we don't do so here
2735 
2736                 return false;
2737             }
2738 
2739             if (!ReplaceStaticLiterals(*bbi))
2740             {
2741                 if (log)
2742                     log->Printf("ReplaceStaticLiterals() failed");
2743 
2744                 return false;
2745             }
2746         }
2747     }
2748 
2749     ////////////////////////////////////////////////////////////////////////
2750     // Run function-level passes that only make sense on the main function
2751     //
2752 
2753     if (!ResolveExternals(*main_function))
2754     {
2755         if (log)
2756             log->Printf("ResolveExternals() failed");
2757 
2758         // ResolveExternals() reports its own errors, so we don't do so here
2759 
2760         return false;
2761     }
2762 
2763     if (!ReplaceVariables(*main_function))
2764     {
2765         if (log)
2766             log->Printf("ReplaceVariables() failed");
2767 
2768         // ReplaceVariables() reports its own errors, so we don't do so here
2769 
2770         return false;
2771     }
2772 
2773     if (!ReplaceStrings())
2774     {
2775         if (log)
2776             log->Printf("ReplaceStrings() failed");
2777 
2778         return false;
2779     }
2780 
2781     if (!CompleteDataAllocation())
2782     {
2783         if (log)
2784             log->Printf("CompleteDataAllocation() failed");
2785 
2786         return false;
2787     }
2788 
2789     if (!StripAllGVs(llvm_module))
2790     {
2791         if (log)
2792             log->Printf("StripAllGVs() failed");
2793     }
2794 
2795     if (log && log->GetVerbose())
2796     {
2797         std::string s;
2798         raw_string_ostream oss(s);
2799 
2800         m_module->print(oss, NULL);
2801 
2802         oss.flush();
2803 
2804         log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
2805     }
2806 
2807     return true;
2808 }
2809 
2810 void
assignPassManager(PMStack & pass_mgr_stack,PassManagerType pass_mgr_type)2811 IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
2812 {
2813 }
2814 
2815 PassManagerType
getPotentialPassManagerType() const2816 IRForTarget::getPotentialPassManagerType() const
2817 {
2818     return PMT_ModulePassManager;
2819 }
2820