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 "IRForTarget.h"
11 
12 #include "ClangExpressionDeclMap.h"
13 
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/IR/Constants.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/InstrTypes.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/Intrinsics.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/LegacyPassManager.h"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/IR/Metadata.h"
24 #include "llvm/IR/ValueSymbolTable.h"
25 
26 #include "clang/AST/ASTContext.h"
27 
28 #include "lldb/Core/ConstString.h"
29 #include "lldb/Core/DataBufferHeap.h"
30 #include "lldb/Core/Log.h"
31 #include "lldb/Core/Scalar.h"
32 #include "lldb/Core/StreamString.h"
33 #include "lldb/Core/dwarf.h"
34 #include "lldb/Expression/IRExecutionUnit.h"
35 #include "lldb/Expression/IRInterpreter.h"
36 #include "lldb/Host/Endian.h"
37 #include "lldb/Symbol/ClangASTContext.h"
38 #include "lldb/Symbol/ClangUtil.h"
39 #include "lldb/Symbol/CompilerType.h"
40 
41 #include <map>
42 
43 using namespace llvm;
44 
45 static char ID;
46 
47 IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) :
48     m_maker(maker),
49     m_values()
50 {
51 }
52 
53 IRForTarget::FunctionValueCache::~FunctionValueCache()
54 {
55 }
56 
57 llvm::Value *
58 IRForTarget::FunctionValueCache::GetValue(llvm::Function *function)
59 {
60     if (!m_values.count(function))
61     {
62         llvm::Value *ret = m_maker(function);
63         m_values[function] = ret;
64         return ret;
65     }
66     return m_values[function];
67 }
68 
69 static llvm::Value *
70 FindEntryInstruction (llvm::Function *function)
71 {
72     if (function->empty())
73         return NULL;
74 
75     return function->getEntryBlock().getFirstNonPHIOrDbg();
76 }
77 
78 IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
79                           bool resolve_vars,
80                           lldb_private::IRExecutionUnit &execution_unit,
81                           lldb_private::Stream *error_stream,
82                           const char *func_name) :
83     ModulePass(ID),
84     m_resolve_vars(resolve_vars),
85     m_func_name(func_name),
86     m_module(NULL),
87     m_decl_map(decl_map),
88     m_CFStringCreateWithBytes(NULL),
89     m_sel_registerName(NULL),
90     m_intptr_ty(NULL),
91     m_error_stream(error_stream),
92     m_execution_unit(execution_unit),
93     m_result_store(NULL),
94     m_result_is_pointer(false),
95     m_reloc_placeholder(NULL),
96     m_entry_instruction_finder (FindEntryInstruction)
97 {
98 }
99 
100 /* Handy utility functions used at several places in the code */
101 
102 static std::string
103 PrintValue(const Value *value, bool truncate = false)
104 {
105     std::string s;
106     if (value)
107     {
108         raw_string_ostream rso(s);
109         value->print(rso);
110         rso.flush();
111         if (truncate)
112             s.resize(s.length() - 1);
113     }
114     return s;
115 }
116 
117 static std::string
118 PrintType(const llvm::Type *type, bool truncate = false)
119 {
120     std::string s;
121     raw_string_ostream rso(s);
122     type->print(rso);
123     rso.flush();
124     if (truncate)
125         s.resize(s.length() - 1);
126     return s;
127 }
128 
129 IRForTarget::~IRForTarget()
130 {
131 }
132 
133 bool
134 IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
135 {
136     llvm_function.setLinkage(GlobalValue::ExternalLinkage);
137 
138     return true;
139 }
140 
141 clang::NamedDecl *
142 IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
143 {
144     NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
145 
146     if (!named_metadata)
147         return NULL;
148 
149     unsigned num_nodes = named_metadata->getNumOperands();
150     unsigned node_index;
151 
152     for (node_index = 0;
153          node_index < num_nodes;
154          ++node_index)
155     {
156         llvm::MDNode *metadata_node = dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index));
157         if (!metadata_node)
158             return NULL;
159 
160         if (metadata_node->getNumOperands() != 2)
161             continue;
162 
163         if (mdconst::dyn_extract_or_null<GlobalValue>(metadata_node->getOperand(0)) != global_val)
164             continue;
165 
166         ConstantInt *constant_int = mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1));
167 
168         if (!constant_int)
169             return NULL;
170 
171         uintptr_t ptr = constant_int->getZExtValue();
172 
173         return reinterpret_cast<clang::NamedDecl *>(ptr);
174     }
175 
176     return NULL;
177 }
178 
179 clang::NamedDecl *
180 IRForTarget::DeclForGlobal (GlobalValue *global_val)
181 {
182     return DeclForGlobal(global_val, m_module);
183 }
184 
185 bool
186 IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
187 {
188     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
189 
190     if (!m_resolve_vars)
191         return true;
192 
193     // Find the result variable.  If it doesn't exist, we can give up right here.
194 
195     ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
196 
197     std::string result_name_str;
198     const char *result_name = NULL;
199 
200     for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
201          vi != ve;
202          ++vi)
203     {
204         result_name_str = vi->first().str();
205         const char *value_name = result_name_str.c_str();
206 
207         if (strstr(value_name, "$__lldb_expr_result_ptr") &&
208             strncmp(value_name, "_ZGV", 4))
209         {
210             result_name = value_name;
211             m_result_is_pointer = true;
212             break;
213         }
214 
215         if (strstr(value_name, "$__lldb_expr_result") &&
216             strncmp(value_name, "_ZGV", 4))
217         {
218             result_name = value_name;
219             m_result_is_pointer = false;
220             break;
221         }
222     }
223 
224     if (!result_name)
225     {
226         if (log)
227             log->PutCString("Couldn't find result variable");
228 
229         return true;
230     }
231 
232     if (log)
233         log->Printf("Result name: \"%s\"", result_name);
234 
235     Value *result_value = m_module->getNamedValue(result_name);
236 
237     if (!result_value)
238     {
239         if (log)
240             log->PutCString("Result variable had no data");
241 
242         if (m_error_stream)
243             m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
244 
245         return false;
246     }
247 
248     if (log)
249         log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
250 
251     GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
252 
253     if (!result_global)
254     {
255         if (log)
256             log->PutCString("Result variable isn't a GlobalVariable");
257 
258         if (m_error_stream)
259             m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
260 
261         return false;
262     }
263 
264     clang::NamedDecl *result_decl = DeclForGlobal (result_global);
265     if (!result_decl)
266     {
267         if (log)
268             log->PutCString("Result variable doesn't have a corresponding Decl");
269 
270         if (m_error_stream)
271             m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
272 
273         return false;
274     }
275 
276     if (log)
277     {
278         std::string decl_desc_str;
279         raw_string_ostream decl_desc_stream(decl_desc_str);
280         result_decl->print(decl_desc_stream);
281         decl_desc_stream.flush();
282 
283         log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
284     }
285 
286     clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
287     if (!result_var)
288     {
289         if (log)
290             log->PutCString("Result variable Decl isn't a VarDecl");
291 
292         if (m_error_stream)
293             m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
294 
295         return false;
296     }
297 
298     // Get the next available result name from m_decl_map and create the persistent
299     // variable for it
300 
301     // If the result is an Lvalue, it is emitted as a pointer; see
302     // ASTResultSynthesizer::SynthesizeBodyResult.
303     if (m_result_is_pointer)
304     {
305         clang::QualType pointer_qual_type = result_var->getType();
306         const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
307 
308         const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
309         const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
310 
311         if (pointer_pointertype)
312         {
313             clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
314 
315             m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
316                                                          lldb_private::ClangASTContext::GetASTContext(&result_decl->getASTContext()));
317         }
318         else if (pointer_objcobjpointertype)
319         {
320             clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
321 
322             m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
323                                                          lldb_private::ClangASTContext::GetASTContext(&result_decl->getASTContext()));
324         }
325         else
326         {
327             if (log)
328                 log->PutCString("Expected result to have pointer type, but it did not");
329 
330             if (m_error_stream)
331                 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
332 
333             return false;
334         }
335     }
336     else
337     {
338         m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
339                                                      lldb_private::ClangASTContext::GetASTContext(&result_decl->getASTContext()));
340     }
341 
342 
343     lldb::TargetSP target_sp (m_execution_unit.GetTarget());
344     lldb_private::ExecutionContext exe_ctx (target_sp, true);
345     if (m_result_type.GetBitSize(exe_ctx.GetBestExecutionContextScope()) == 0)
346     {
347         lldb_private::StreamString type_desc_stream;
348         m_result_type.DumpTypeDescription(&type_desc_stream);
349 
350         if (log)
351             log->Printf("Result type has size 0");
352 
353         if (m_error_stream)
354             m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
355                                    type_desc_stream.GetData());
356         return false;
357     }
358 
359     if (log)
360     {
361         lldb_private::StreamString type_desc_stream;
362         m_result_type.DumpTypeDescription(&type_desc_stream);
363 
364         log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
365     }
366 
367     m_result_name = lldb_private::ConstString("$RESULT_NAME");
368 
369     if (log)
370         log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
371                     m_result_name.GetCString(),
372                     m_result_type.GetByteSize(nullptr));
373 
374     // Construct a new result global and set up its metadata
375 
376     GlobalVariable *new_result_global = new GlobalVariable((*m_module),
377                                                            result_global->getType()->getElementType(),
378                                                            false, /* not constant */
379                                                            GlobalValue::ExternalLinkage,
380                                                            NULL, /* no initializer */
381                                                            m_result_name.GetCString ());
382 
383     // It's too late in compilation to create a new VarDecl for this, but we don't
384     // need to.  We point the metadata at the old VarDecl.  This creates an odd
385     // anomaly: a variable with a Value whose name is something like $0 and a
386     // Decl whose name is $__lldb_expr_result.  This condition is handled in
387     // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
388     // fixed up.
389 
390     ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
391                                                      reinterpret_cast<uint64_t>(result_decl),
392                                                      false);
393 
394     llvm::Metadata *values[2];
395     values[0] = ConstantAsMetadata::get(new_result_global);
396     values[1] = ConstantAsMetadata::get(new_constant_int);
397 
398     ArrayRef<Metadata *> value_ref(values, 2);
399 
400     MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
401     NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
402     named_metadata->addOperand(persistent_global_md);
403 
404     if (log)
405         log->Printf("Replacing \"%s\" with \"%s\"",
406                     PrintValue(result_global).c_str(),
407                     PrintValue(new_result_global).c_str());
408 
409     if (result_global->use_empty())
410     {
411         // We need to synthesize a store for this variable, because otherwise
412         // there's nothing to put into its equivalent persistent variable.
413 
414         BasicBlock &entry_block(llvm_function.getEntryBlock());
415         Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
416 
417         if (!first_entry_instruction)
418             return false;
419 
420         if (!result_global->hasInitializer())
421         {
422             if (log)
423                 log->Printf("Couldn't find initializer for unused variable");
424 
425             if (m_error_stream)
426                 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
427 
428             return false;
429         }
430 
431         Constant *initializer = result_global->getInitializer();
432 
433         StoreInst *synthesized_store = new StoreInst(initializer,
434                                                      new_result_global,
435                                                      first_entry_instruction);
436 
437         if (log)
438             log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
439     }
440     else
441     {
442         result_global->replaceAllUsesWith(new_result_global);
443     }
444 
445     if (!m_decl_map->AddPersistentVariable(result_decl,
446                                            m_result_name,
447                                            m_result_type,
448                                            true,
449                                            m_result_is_pointer))
450         return false;
451 
452     result_global->eraseFromParent();
453 
454     return true;
455 }
456 
457 bool
458 IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
459                                      llvm::GlobalVariable *cstr)
460 {
461     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
462 
463     Type *ns_str_ty = ns_str->getType();
464 
465     Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
466     Type *i32_ty = Type::getInt32Ty(m_module->getContext());
467     Type *i8_ty = Type::getInt8Ty(m_module->getContext());
468 
469     if (!m_CFStringCreateWithBytes)
470     {
471         lldb::addr_t CFStringCreateWithBytes_addr;
472 
473         static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
474 
475         CFStringCreateWithBytes_addr = m_execution_unit.FindSymbol (g_CFStringCreateWithBytes_str);
476         if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS)
477         {
478             if (log)
479                 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
480 
481             if (m_error_stream)
482                 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
483 
484             return false;
485         }
486 
487         if (log)
488             log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
489 
490         // Build the function type:
491         //
492         // CFStringRef CFStringCreateWithBytes (
493         //   CFAllocatorRef alloc,
494         //   const UInt8 *bytes,
495         //   CFIndex numBytes,
496         //   CFStringEncoding encoding,
497         //   Boolean isExternalRepresentation
498         // );
499         //
500         // We make the following substitutions:
501         //
502         // CFStringRef -> i8*
503         // CFAllocatorRef -> i8*
504         // UInt8 * -> i8*
505         // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
506         // CFStringEncoding -> i32
507         // Boolean -> i8
508 
509         Type *arg_type_array[5];
510 
511         arg_type_array[0] = i8_ptr_ty;
512         arg_type_array[1] = i8_ptr_ty;
513         arg_type_array[2] = m_intptr_ty;
514         arg_type_array[3] = i32_ty;
515         arg_type_array[4] = i8_ty;
516 
517         ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
518 
519         llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
520 
521         // Build the constant containing the pointer to the function
522         PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
523         Constant *CFSCWB_addr_int = ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
524         m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
525     }
526 
527     ConstantDataSequential *string_array = NULL;
528 
529     if (cstr)
530         string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
531 
532     Constant *alloc_arg         = Constant::getNullValue(i8_ptr_ty);
533     Constant *bytes_arg         = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
534     Constant *numBytes_arg      = ConstantInt::get(m_intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
535     Constant *encoding_arg      = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
536     Constant *isExternal_arg    = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
537 
538     Value *argument_array[5];
539 
540     argument_array[0] = alloc_arg;
541     argument_array[1] = bytes_arg;
542     argument_array[2] = numBytes_arg;
543     argument_array[3] = encoding_arg;
544     argument_array[4] = isExternal_arg;
545 
546     ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
547 
548     FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
549         return CallInst::Create(m_CFStringCreateWithBytes,
550                                 CFSCWB_arguments,
551                                 "CFStringCreateWithBytes",
552                                 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
553     });
554 
555     if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
556     {
557         if (log)
558             log->PutCString("Couldn't replace the NSString with the result of the call");
559 
560         if (m_error_stream)
561             m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
562 
563         return false;
564     }
565 
566     ns_str->eraseFromParent();
567 
568     return true;
569 }
570 
571 bool
572 IRForTarget::RewriteObjCConstStrings()
573 {
574     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
575 
576     ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
577 
578     for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
579          vi != ve;
580          ++vi)
581     {
582         std::string value_name = vi->first().str();
583         const char *value_name_cstr = value_name.c_str();
584 
585         if (strstr(value_name_cstr, "_unnamed_cfstring_"))
586         {
587             Value *nsstring_value = vi->second;
588 
589             GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
590 
591             if (!nsstring_global)
592             {
593                 if (log)
594                     log->PutCString("NSString variable is not a GlobalVariable");
595 
596                 if (m_error_stream)
597                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
598 
599                 return false;
600             }
601 
602             if (!nsstring_global->hasInitializer())
603             {
604                 if (log)
605                     log->PutCString("NSString variable does not have an initializer");
606 
607                 if (m_error_stream)
608                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
609 
610                 return false;
611             }
612 
613             ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
614 
615             if (!nsstring_struct)
616             {
617                 if (log)
618                     log->PutCString("NSString variable's initializer is not a ConstantStruct");
619 
620                 if (m_error_stream)
621                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
622 
623                 return false;
624             }
625 
626             // We expect the following structure:
627             //
628             // struct {
629             //   int *isa;
630             //   int flags;
631             //   char *str;
632             //   long length;
633             // };
634 
635             if (nsstring_struct->getNumOperands() != 4)
636             {
637                 if (log)
638                     log->Printf("NSString variable's initializer structure has an unexpected number of members.  Should be 4, is %d", nsstring_struct->getNumOperands());
639 
640                 if (m_error_stream)
641                     m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
642 
643                 return false;
644             }
645 
646             Constant *nsstring_member = nsstring_struct->getOperand(2);
647 
648             if (!nsstring_member)
649             {
650                 if (log)
651                     log->PutCString("NSString initializer's str element was empty");
652 
653                 if (m_error_stream)
654                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
655 
656                 return false;
657             }
658 
659             ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
660 
661             if (!nsstring_expr)
662             {
663                 if (log)
664                     log->PutCString("NSString initializer's str element is not a ConstantExpr");
665 
666                 if (m_error_stream)
667                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
668 
669                 return false;
670             }
671 
672             if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
673             {
674                 if (log)
675                     log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
676 
677                 if (m_error_stream)
678                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
679 
680                 return false;
681             }
682 
683             Constant *nsstring_cstr = nsstring_expr->getOperand(0);
684 
685             GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
686 
687             if (!cstr_global)
688             {
689                 if (log)
690                     log->PutCString("NSString initializer's str element is not a GlobalVariable");
691 
692                 if (m_error_stream)
693                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
694 
695                 return false;
696             }
697 
698             if (!cstr_global->hasInitializer())
699             {
700                 if (log)
701                     log->PutCString("NSString initializer's str element does not have an initializer");
702 
703                 if (m_error_stream)
704                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
705 
706                 return false;
707             }
708 
709             /*
710             if (!cstr_array)
711             {
712                 if (log)
713                     log->PutCString("NSString initializer's str element is not a ConstantArray");
714 
715                 if (m_error_stream)
716                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
717 
718                 return false;
719             }
720 
721             if (!cstr_array->isCString())
722             {
723                 if (log)
724                     log->PutCString("NSString initializer's str element is not a C string array");
725 
726                 if (m_error_stream)
727                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
728 
729                 return false;
730             }
731             */
732 
733             ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
734 
735             if (log)
736             {
737                 if (cstr_array)
738                     log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().str().c_str());
739                 else
740                     log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
741             }
742 
743             if (!cstr_array)
744                 cstr_global = NULL;
745 
746             if (!RewriteObjCConstString(nsstring_global, cstr_global))
747             {
748                 if (log)
749                     log->PutCString("Error rewriting the constant string");
750 
751                 // We don't print an error message here because RewriteObjCConstString has done so for us.
752 
753                 return false;
754             }
755         }
756     }
757 
758     for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
759          vi != ve;
760          ++vi)
761     {
762         std::string value_name = vi->first().str();
763         const char *value_name_cstr = value_name.c_str();
764 
765         if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
766         {
767             GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
768 
769             if (!gv)
770             {
771                 if (log)
772                     log->PutCString("__CFConstantStringClassReference is not a global variable");
773 
774                 if (m_error_stream)
775                     m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
776 
777                 return false;
778             }
779 
780             gv->eraseFromParent();
781 
782             break;
783         }
784     }
785 
786     return true;
787 }
788 
789 static bool IsObjCSelectorRef (Value *value)
790 {
791     GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
792 
793     if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("OBJC_SELECTOR_REFERENCES_"))
794         return false;
795 
796     return true;
797 }
798 
799 // This function does not report errors; its callers are responsible.
800 bool
801 IRForTarget::RewriteObjCSelector (Instruction* selector_load)
802 {
803     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
804 
805     LoadInst *load = dyn_cast<LoadInst>(selector_load);
806 
807     if (!load)
808         return false;
809 
810     // Unpack the message name from the selector.  In LLVM IR, an objc_msgSend gets represented as
811     //
812     // %tmp     = load i8** @"OBJC_SELECTOR_REFERENCES_" ; <i8*>
813     // %call    = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
814     //
815     // where %obj is the object pointer and %tmp is the selector.
816     //
817     // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
818     // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
819 
820     // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
821 
822     GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
823 
824     if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
825         return false;
826 
827     Constant *osr_initializer = _objc_selector_references_->getInitializer();
828 
829     ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
830 
831     if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
832         return false;
833 
834     Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
835 
836     if (!osr_initializer_base)
837         return false;
838 
839     // Find the string's initializer (a ConstantArray) and get the string from it
840 
841     GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
842 
843     if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
844         return false;
845 
846     Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
847 
848     ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
849 
850     if (!omvn_initializer_array->isString())
851         return false;
852 
853     std::string omvn_initializer_string = omvn_initializer_array->getAsString();
854 
855     if (log)
856         log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
857 
858     // Construct a call to sel_registerName
859 
860     if (!m_sel_registerName)
861     {
862         lldb::addr_t sel_registerName_addr;
863 
864         static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
865         sel_registerName_addr = m_execution_unit.FindSymbol (g_sel_registerName_str);
866         if (sel_registerName_addr == LLDB_INVALID_ADDRESS)
867             return false;
868 
869         if (log)
870             log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
871 
872         // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
873 
874         // The below code would be "more correct," but in actuality what's required is uint8_t*
875         //Type *sel_type = StructType::get(m_module->getContext());
876         //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
877         Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
878 
879         Type *type_array[1];
880 
881         type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
882 
883         ArrayRef<Type *> srN_arg_types(type_array, 1);
884 
885         llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
886 
887         // Build the constant containing the pointer to the function
888         PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
889         Constant *srN_addr_int = ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
890         m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
891     }
892 
893     Value *argument_array[1];
894 
895     Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
896 
897     argument_array[0] = omvn_pointer;
898 
899     ArrayRef<Value *> srN_arguments(argument_array, 1);
900 
901     CallInst *srN_call = CallInst::Create(m_sel_registerName,
902                                           srN_arguments,
903                                           "sel_registerName",
904                                           selector_load);
905 
906     // Replace the load with the call in all users
907 
908     selector_load->replaceAllUsesWith(srN_call);
909 
910     selector_load->eraseFromParent();
911 
912     return true;
913 }
914 
915 bool
916 IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
917 {
918     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
919 
920     BasicBlock::iterator ii;
921 
922     typedef SmallVector <Instruction*, 2> InstrList;
923     typedef InstrList::iterator InstrIterator;
924 
925     InstrList selector_loads;
926 
927     for (ii = basic_block.begin();
928          ii != basic_block.end();
929          ++ii)
930     {
931         Instruction &inst = *ii;
932 
933         if (LoadInst *load = dyn_cast<LoadInst>(&inst))
934             if (IsObjCSelectorRef(load->getPointerOperand()))
935                 selector_loads.push_back(&inst);
936     }
937 
938     InstrIterator iter;
939 
940     for (iter = selector_loads.begin();
941          iter != selector_loads.end();
942          ++iter)
943     {
944         if (!RewriteObjCSelector(*iter))
945         {
946             if (m_error_stream)
947                 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
948 
949             if (log)
950                 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
951 
952             return false;
953         }
954     }
955 
956     return true;
957 }
958 
959 // This function does not report errors; its callers are responsible.
960 bool
961 IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
962 {
963     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
964 
965     AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
966 
967     MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
968 
969     if (!alloc_md || !alloc_md->getNumOperands())
970         return false;
971 
972     ConstantInt *constant_int = mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0));
973 
974     if (!constant_int)
975         return false;
976 
977     // We attempt to register this as a new persistent variable with the DeclMap.
978 
979     uintptr_t ptr = constant_int->getZExtValue();
980 
981     clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
982 
983     lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
984                                                    lldb_private::ClangASTContext::GetASTContext(&decl->getASTContext()));
985 
986     StringRef decl_name (decl->getName());
987     lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
988     if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
989         return false;
990 
991     GlobalVariable *persistent_global = new GlobalVariable((*m_module),
992                                                            alloc->getType(),
993                                                            false, /* not constant */
994                                                            GlobalValue::ExternalLinkage,
995                                                            NULL, /* no initializer */
996                                                            alloc->getName().str().c_str());
997 
998     // What we're going to do here is make believe this was a regular old external
999     // variable.  That means we need to make the metadata valid.
1000 
1001     NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
1002 
1003     llvm::Metadata *values[2];
1004     values[0] = ConstantAsMetadata::get(persistent_global);
1005     values[1] = ConstantAsMetadata::get(constant_int);
1006 
1007     ArrayRef<llvm::Metadata *> value_ref(values, 2);
1008 
1009     MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
1010     named_metadata->addOperand(persistent_global_md);
1011 
1012     // Now, since the variable is a pointer variable, we will drop in a load of that
1013     // pointer variable.
1014 
1015     LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1016 
1017     if (log)
1018         log->Printf("Replacing \"%s\" with \"%s\"",
1019                     PrintValue(alloc).c_str(),
1020                     PrintValue(persistent_load).c_str());
1021 
1022     alloc->replaceAllUsesWith(persistent_load);
1023     alloc->eraseFromParent();
1024 
1025     return true;
1026 }
1027 
1028 bool
1029 IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
1030 {
1031     if (!m_resolve_vars)
1032         return true;
1033 
1034     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1035 
1036     BasicBlock::iterator ii;
1037 
1038     typedef SmallVector <Instruction*, 2> InstrList;
1039     typedef InstrList::iterator InstrIterator;
1040 
1041     InstrList pvar_allocs;
1042 
1043     for (ii = basic_block.begin();
1044          ii != basic_block.end();
1045          ++ii)
1046     {
1047         Instruction &inst = *ii;
1048 
1049         if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
1050         {
1051             llvm::StringRef alloc_name = alloc->getName();
1052 
1053             if (alloc_name.startswith("$") &&
1054                 !alloc_name.startswith("$__lldb"))
1055             {
1056                 if (alloc_name.find_first_of("0123456789") == 1)
1057                 {
1058                     if (log)
1059                         log->Printf("Rejecting a numeric persistent variable.");
1060 
1061                     if (m_error_stream)
1062                         m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1063 
1064                     return false;
1065                 }
1066 
1067                 pvar_allocs.push_back(alloc);
1068             }
1069         }
1070     }
1071 
1072     InstrIterator iter;
1073 
1074     for (iter = pvar_allocs.begin();
1075          iter != pvar_allocs.end();
1076          ++iter)
1077     {
1078         if (!RewritePersistentAlloc(*iter))
1079         {
1080             if (m_error_stream)
1081                 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1082 
1083             if (log)
1084                 log->PutCString("Couldn't rewrite the creation of a persistent variable");
1085 
1086             return false;
1087         }
1088     }
1089 
1090     return true;
1091 }
1092 
1093 bool
1094 IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1095 {
1096     if (!initializer)
1097         return true;
1098 
1099     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1100 
1101     if (log && log->GetVerbose())
1102         log->Printf("  MaterializeInitializer(%p, %s)", (void *)data, PrintValue(initializer).c_str());
1103 
1104     Type *initializer_type = initializer->getType();
1105 
1106     if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1107     {
1108         memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1109         return true;
1110     }
1111     else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
1112     {
1113         if (array_initializer->isString())
1114         {
1115             std::string array_initializer_string = array_initializer->getAsString();
1116             memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1117         }
1118         else
1119         {
1120             ArrayType *array_initializer_type = array_initializer->getType();
1121             Type *array_element_type = array_initializer_type->getElementType();
1122 
1123             size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1124 
1125             for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
1126             {
1127                 Value *operand_value = array_initializer->getOperand(i);
1128                 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1129 
1130                 if (!operand_constant)
1131                     return false;
1132 
1133                 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
1134                     return false;
1135             }
1136         }
1137         return true;
1138     }
1139     else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1140     {
1141         StructType *struct_initializer_type = struct_initializer->getType();
1142         const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1143 
1144         for (unsigned i = 0;
1145              i < struct_initializer->getNumOperands();
1146              ++i)
1147         {
1148             if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1149                 return false;
1150         }
1151         return true;
1152     }
1153     else if (isa<ConstantAggregateZero>(initializer))
1154     {
1155         memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1156         return true;
1157     }
1158     return false;
1159 }
1160 
1161 // This function does not report errors; its callers are responsible.
1162 bool
1163 IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
1164 {
1165     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1166 
1167     if (log)
1168         log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
1169 
1170     if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
1171     {
1172         switch (constant_expr->getOpcode())
1173         {
1174         default:
1175             break;
1176         case Instruction::GetElementPtr:
1177         case Instruction::BitCast:
1178             Value *s = constant_expr->getOperand(0);
1179             if (!MaybeHandleVariable(s))
1180                 return false;
1181         }
1182     }
1183     else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
1184     {
1185         if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1186             return true;
1187 
1188         clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1189 
1190         if (!named_decl)
1191         {
1192             if (IsObjCSelectorRef(llvm_value_ptr))
1193                 return true;
1194 
1195             if (!global_variable->hasExternalLinkage())
1196                 return true;
1197 
1198             if (log)
1199                 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
1200 
1201             return false;
1202         }
1203 
1204         std::string name (named_decl->getName().str());
1205 
1206         clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1207         if (value_decl == NULL)
1208             return false;
1209 
1210         lldb_private::CompilerType compiler_type(&value_decl->getASTContext(), value_decl->getType());
1211 
1212         const Type *value_type = NULL;
1213 
1214         if (name[0] == '$')
1215         {
1216             // The $__lldb_expr_result name indicates the return value has allocated as
1217             // a static variable.  Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1218             // accesses to this static variable need to be redirected to the result of dereferencing
1219             // a pointer that is passed in as one of the arguments.
1220             //
1221             // Consequently, when reporting the size of the type, we report a pointer type pointing
1222             // to the type of $__lldb_expr_result, not the type itself.
1223             //
1224             // We also do this for any user-declared persistent variables.
1225             compiler_type = compiler_type.GetPointerType();
1226             value_type = PointerType::get(global_variable->getType(), 0);
1227         }
1228         else
1229         {
1230             value_type = global_variable->getType();
1231         }
1232 
1233         const uint64_t value_size = compiler_type.GetByteSize(nullptr);
1234         lldb::offset_t value_alignment = (compiler_type.GetTypeBitAlign() + 7ull) / 8ull;
1235 
1236         if (log)
1237         {
1238             log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRIu64 "]",
1239                         name.c_str(), lldb_private::ClangUtil::GetQualType(compiler_type).getAsString().c_str(),
1240                         PrintType(value_type).c_str(), value_size, value_alignment);
1241         }
1242 
1243 
1244         if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
1245                                                         lldb_private::ConstString (name.c_str()),
1246                                                         llvm_value_ptr,
1247                                                         value_size,
1248                                                         value_alignment))
1249         {
1250             if (!global_variable->hasExternalLinkage())
1251                 return true;
1252             else
1253                 return true;
1254         }
1255     }
1256     else if (dyn_cast<llvm::Function>(llvm_value_ptr))
1257     {
1258         if (log)
1259             log->Printf("Function pointers aren't handled right now");
1260 
1261         return false;
1262     }
1263 
1264     return true;
1265 }
1266 
1267 // This function does not report errors; its callers are responsible.
1268 bool
1269 IRForTarget::HandleSymbol (Value *symbol)
1270 {
1271     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1272 
1273     lldb_private::ConstString name(symbol->getName().str().c_str());
1274 
1275     lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
1276 
1277     if (symbol_addr == LLDB_INVALID_ADDRESS)
1278     {
1279         if (log)
1280             log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1281 
1282         return false;
1283     }
1284 
1285     if (log)
1286         log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
1287 
1288     Type *symbol_type = symbol->getType();
1289 
1290     Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
1291 
1292     Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1293 
1294     if (log)
1295         log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1296 
1297     symbol->replaceAllUsesWith(symbol_addr_ptr);
1298 
1299     return true;
1300 }
1301 
1302 bool
1303 IRForTarget::MaybeHandleCallArguments (CallInst *Old)
1304 {
1305     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1306 
1307     if (log)
1308         log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
1309 
1310     for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
1311          op_index < num_ops;
1312          ++op_index)
1313         if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
1314         {
1315             if (m_error_stream)
1316                 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1317 
1318             return false;
1319         }
1320 
1321     return true;
1322 }
1323 
1324 bool
1325 IRForTarget::HandleObjCClass(Value *classlist_reference)
1326 {
1327     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1328 
1329     GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1330 
1331     if (!global_variable)
1332         return false;
1333 
1334     Constant *initializer = global_variable->getInitializer();
1335 
1336     if (!initializer)
1337         return false;
1338 
1339     if (!initializer->hasName())
1340         return false;
1341 
1342     StringRef name(initializer->getName());
1343     lldb_private::ConstString name_cstr(name.str().c_str());
1344     lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1345 
1346     if (log)
1347         log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1348 
1349     if (class_ptr == LLDB_INVALID_ADDRESS)
1350         return false;
1351 
1352     if (global_variable->use_empty())
1353         return false;
1354 
1355     SmallVector<LoadInst *, 2> load_instructions;
1356 
1357     for (llvm::User *u : global_variable->users())
1358     {
1359         if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1360             load_instructions.push_back(load_instruction);
1361     }
1362 
1363     if (load_instructions.empty())
1364         return false;
1365 
1366     Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
1367 
1368     for (LoadInst *load_instruction : load_instructions)
1369     {
1370         Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1371 
1372         load_instruction->replaceAllUsesWith(class_bitcast);
1373 
1374         load_instruction->eraseFromParent();
1375     }
1376 
1377     return true;
1378 }
1379 
1380 bool
1381 IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1382 {
1383     BasicBlock::iterator ii;
1384 
1385     std::vector<CallInst *> calls_to_remove;
1386 
1387     for (ii = basic_block.begin();
1388          ii != basic_block.end();
1389          ++ii)
1390     {
1391         Instruction &inst = *ii;
1392 
1393         CallInst *call = dyn_cast<CallInst>(&inst);
1394 
1395         // MaybeHandleCallArguments handles error reporting; we are silent here
1396         if (!call)
1397             continue;
1398 
1399         bool remove = false;
1400 
1401         llvm::Function *func = call->getCalledFunction();
1402 
1403         if (func && func->getName() == "__cxa_atexit")
1404             remove = true;
1405 
1406         llvm::Value *val = call->getCalledValue();
1407 
1408         if (val && val->getName() == "__cxa_atexit")
1409             remove = true;
1410 
1411         if (remove)
1412             calls_to_remove.push_back(call);
1413     }
1414 
1415     for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1416          ci != ce;
1417          ++ci)
1418     {
1419         (*ci)->eraseFromParent();
1420     }
1421 
1422     return true;
1423 }
1424 
1425 bool
1426 IRForTarget::ResolveCalls(BasicBlock &basic_block)
1427 {
1428     /////////////////////////////////////////////////////////////////////////
1429     // Prepare the current basic block for execution in the remote process
1430     //
1431 
1432     BasicBlock::iterator ii;
1433 
1434     for (ii = basic_block.begin();
1435          ii != basic_block.end();
1436          ++ii)
1437     {
1438         Instruction &inst = *ii;
1439 
1440         CallInst *call = dyn_cast<CallInst>(&inst);
1441 
1442         // MaybeHandleCallArguments handles error reporting; we are silent here
1443         if (call && !MaybeHandleCallArguments(call))
1444             return false;
1445     }
1446 
1447     return true;
1448 }
1449 
1450 bool
1451 IRForTarget::ResolveExternals (Function &llvm_function)
1452 {
1453     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1454 
1455     for (GlobalVariable &global_var : m_module->globals())
1456     {
1457         std::string global_name = global_var.getName().str();
1458 
1459         if (log)
1460             log->Printf("Examining %s, DeclForGlobalValue returns %p",
1461                         global_name.c_str(),
1462                         static_cast<void*>(DeclForGlobal(&global_var)));
1463 
1464         if (global_name.find("OBJC_IVAR") == 0)
1465         {
1466             if (!HandleSymbol(&global_var))
1467             {
1468                 if (m_error_stream)
1469                     m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", global_name.c_str());
1470 
1471                 return false;
1472             }
1473         }
1474         else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1475         {
1476             if (!HandleObjCClass(&global_var))
1477             {
1478                 if (m_error_stream)
1479                     m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1480 
1481                 return false;
1482             }
1483         }
1484         else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1485         {
1486             if (!HandleObjCClass(&global_var))
1487             {
1488                 if (m_error_stream)
1489                     m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1490 
1491                 return false;
1492             }
1493         }
1494         else if (DeclForGlobal(&global_var))
1495         {
1496             if (!MaybeHandleVariable (&global_var))
1497             {
1498                 if (m_error_stream)
1499                     m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", global_name.c_str());
1500 
1501                 return false;
1502             }
1503         }
1504     }
1505 
1506     return true;
1507 }
1508 
1509 static bool isGuardVariableRef(Value *V)
1510 {
1511     Constant *Old = NULL;
1512 
1513     if (!(Old = dyn_cast<Constant>(V)))
1514         return false;
1515 
1516     ConstantExpr *CE = NULL;
1517 
1518     if ((CE = dyn_cast<ConstantExpr>(V)))
1519     {
1520         if (CE->getOpcode() != Instruction::BitCast)
1521             return false;
1522 
1523         Old = CE->getOperand(0);
1524     }
1525 
1526     GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
1527 
1528     if (!GV || !GV->hasName() ||
1529         (!GV->getName().startswith("_ZGV") && // Itanium ABI guard variable
1530          !GV->getName().endswith("@4IA")))    // Microsoft ABI guard variable
1531     {
1532         return false;
1533     }
1534 
1535     return true;
1536 }
1537 
1538 void
1539 IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
1540 {
1541     Constant *zero(Constant::getNullValue(guard_load->getType()));
1542     guard_load->replaceAllUsesWith(zero);
1543     guard_load->eraseFromParent();
1544 }
1545 
1546 static void ExciseGuardStore(Instruction* guard_store)
1547 {
1548     guard_store->eraseFromParent();
1549 }
1550 
1551 bool
1552 IRForTarget::RemoveGuards(BasicBlock &basic_block)
1553 {
1554     ///////////////////////////////////////////////////////
1555     // Eliminate any reference to guard variables found.
1556     //
1557 
1558     BasicBlock::iterator ii;
1559 
1560     typedef SmallVector <Instruction*, 2> InstrList;
1561     typedef InstrList::iterator InstrIterator;
1562 
1563     InstrList guard_loads;
1564     InstrList guard_stores;
1565 
1566     for (ii = basic_block.begin();
1567          ii != basic_block.end();
1568          ++ii)
1569     {
1570         Instruction &inst = *ii;
1571 
1572         if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1573             if (isGuardVariableRef(load->getPointerOperand()))
1574                 guard_loads.push_back(&inst);
1575 
1576         if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1577             if (isGuardVariableRef(store->getPointerOperand()))
1578                 guard_stores.push_back(&inst);
1579     }
1580 
1581     InstrIterator iter;
1582 
1583     for (iter = guard_loads.begin();
1584          iter != guard_loads.end();
1585          ++iter)
1586         TurnGuardLoadIntoZero(*iter);
1587 
1588     for (iter = guard_stores.begin();
1589          iter != guard_stores.end();
1590          ++iter)
1591         ExciseGuardStore(*iter);
1592 
1593     return true;
1594 }
1595 
1596 // This function does not report errors; its callers are responsible.
1597 bool
1598 IRForTarget::UnfoldConstant(Constant *old_constant,
1599                             FunctionValueCache &value_maker,
1600                             FunctionValueCache &entry_instruction_finder)
1601 {
1602     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1603 
1604     SmallVector<User*, 16> users;
1605 
1606     // We do this because the use list might change, invalidating our iterator.
1607     // Much better to keep a work list ourselves.
1608     for (llvm::User *u : old_constant->users())
1609         users.push_back(u);
1610 
1611     for (size_t i = 0;
1612          i < users.size();
1613          ++i)
1614     {
1615         User *user = users[i];
1616 
1617         if (Constant *constant = dyn_cast<Constant>(user))
1618         {
1619             // synthesize a new non-constant equivalent of the constant
1620 
1621             if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
1622             {
1623                 switch (constant_expr->getOpcode())
1624                 {
1625                 default:
1626                     if (log)
1627                         log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
1628                     return false;
1629                 case Instruction::BitCast:
1630                     {
1631                         FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
1632                             // UnaryExpr
1633                             //   OperandList[0] is value
1634 
1635                             if (constant_expr->getOperand(0) != old_constant)
1636                                 return constant_expr;
1637 
1638                             return new BitCastInst(value_maker.GetValue(function),
1639                                                    constant_expr->getType(),
1640                                                    "",
1641                                                    llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
1642                         });
1643 
1644                         if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder))
1645                             return false;
1646                     }
1647                     break;
1648                 case Instruction::GetElementPtr:
1649                     {
1650                         // GetElementPtrConstantExpr
1651                         //   OperandList[0] is base
1652                         //   OperandList[1]... are indices
1653 
1654                         FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
1655                             Value *ptr = constant_expr->getOperand(0);
1656 
1657                             if (ptr == old_constant)
1658                                 ptr = value_maker.GetValue(function);
1659 
1660                             std::vector<Value*> index_vector;
1661 
1662                             unsigned operand_index;
1663                             unsigned num_operands = constant_expr->getNumOperands();
1664 
1665                             for (operand_index = 1;
1666                                  operand_index < num_operands;
1667                                  ++operand_index)
1668                             {
1669                                 Value *operand = constant_expr->getOperand(operand_index);
1670 
1671                                 if (operand == old_constant)
1672                                     operand = value_maker.GetValue(function);
1673 
1674                                 index_vector.push_back(operand);
1675                             }
1676 
1677                             ArrayRef <Value*> indices(index_vector);
1678 
1679                             return GetElementPtrInst::Create(nullptr, ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
1680                         });
1681 
1682                         if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder))
1683                             return false;
1684                     }
1685                     break;
1686                 }
1687             }
1688             else
1689             {
1690                 if (log)
1691                     log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
1692                 return false;
1693             }
1694         }
1695         else
1696         {
1697             if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
1698             {
1699                 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
1700             }
1701             else
1702             {
1703                 if (log)
1704                     log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
1705                 return false;
1706             }
1707         }
1708     }
1709 
1710     if (!isa<GlobalValue>(old_constant))
1711     {
1712         old_constant->destroyConstant();
1713     }
1714 
1715     return true;
1716 }
1717 
1718 bool
1719 IRForTarget::ReplaceVariables (Function &llvm_function)
1720 {
1721     if (!m_resolve_vars)
1722         return true;
1723 
1724     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1725 
1726     m_decl_map->DoStructLayout();
1727 
1728     if (log)
1729         log->Printf("Element arrangement:");
1730 
1731     uint32_t num_elements;
1732     uint32_t element_index;
1733 
1734     size_t size;
1735     lldb::offset_t alignment;
1736 
1737     if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
1738         return false;
1739 
1740     Function::arg_iterator iter(llvm_function.getArgumentList().begin());
1741 
1742     if (iter == llvm_function.getArgumentList().end())
1743     {
1744         if (m_error_stream)
1745             m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
1746 
1747         return false;
1748     }
1749 
1750     Argument *argument = &*iter;
1751 
1752     if (argument->getName().equals("this"))
1753     {
1754         ++iter;
1755 
1756         if (iter == llvm_function.getArgumentList().end())
1757         {
1758             if (m_error_stream)
1759                 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
1760 
1761             return false;
1762         }
1763 
1764         argument = &*iter;
1765     }
1766     else if (argument->getName().equals("self"))
1767     {
1768         ++iter;
1769 
1770         if (iter == llvm_function.getArgumentList().end())
1771         {
1772             if (m_error_stream)
1773                 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
1774 
1775             return false;
1776         }
1777 
1778         if (!iter->getName().equals("_cmd"))
1779         {
1780             if (m_error_stream)
1781                 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
1782 
1783             return false;
1784         }
1785 
1786         ++iter;
1787 
1788         if (iter == llvm_function.getArgumentList().end())
1789         {
1790             if (m_error_stream)
1791                 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
1792 
1793             return false;
1794         }
1795 
1796         argument = &*iter;
1797     }
1798 
1799     if (!argument->getName().equals("$__lldb_arg"))
1800     {
1801         if (m_error_stream)
1802             m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
1803 
1804         return false;
1805     }
1806 
1807     if (log)
1808         log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
1809 
1810     BasicBlock &entry_block(llvm_function.getEntryBlock());
1811     Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
1812 
1813     if (!FirstEntryInstruction)
1814     {
1815         if (m_error_stream)
1816             m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
1817 
1818         return false;
1819     }
1820 
1821     LLVMContext &context(m_module->getContext());
1822     IntegerType *offset_type(Type::getInt32Ty(context));
1823 
1824     if (!offset_type)
1825     {
1826         if (m_error_stream)
1827             m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
1828 
1829         return false;
1830     }
1831 
1832     for (element_index = 0; element_index < num_elements; ++element_index)
1833     {
1834         const clang::NamedDecl *decl = NULL;
1835         Value *value = NULL;
1836         lldb::offset_t offset;
1837         lldb_private::ConstString name;
1838 
1839         if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
1840         {
1841             if (m_error_stream)
1842                 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
1843 
1844             return false;
1845         }
1846 
1847         if (log)
1848             log->Printf("  \"%s\" (\"%s\") placed at %" PRIu64,
1849                         name.GetCString(),
1850                         decl->getNameAsString().c_str(),
1851                         offset);
1852 
1853         if (value)
1854         {
1855             if (log)
1856                 log->Printf("    Replacing [%s]", PrintValue(value).c_str());
1857 
1858             FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
1859                 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
1860                 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
1861                 // entry in order to produce the static variable that the AST thinks it is accessing.
1862 
1863                 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
1864 
1865                 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
1866                 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(nullptr,
1867                                                                                argument,
1868                                                                                offset_int,
1869                                                                                "",
1870                                                                                entry_instruction);
1871 
1872                 if (name == m_result_name && !m_result_is_pointer)
1873                 {
1874                     BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
1875                                                             value->getType()->getPointerTo(),
1876                                                             "",
1877                                                             entry_instruction);
1878 
1879                     LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
1880 
1881                     return load;
1882                 }
1883                 else
1884                 {
1885                     BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
1886 
1887                     return bit_cast;
1888                 }
1889             });
1890 
1891             if (Constant *constant = dyn_cast<Constant>(value))
1892             {
1893                 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
1894             }
1895             else if (Instruction *instruction = dyn_cast<Instruction>(value))
1896             {
1897                 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
1898             }
1899             else
1900             {
1901                 if (log)
1902                     log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
1903                 return false;
1904             }
1905 
1906             if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
1907                 var->eraseFromParent();
1908         }
1909     }
1910 
1911     if (log)
1912         log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]", (int64_t)alignment, (uint64_t)size);
1913 
1914     return true;
1915 }
1916 
1917 llvm::Constant *
1918 IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
1919 {
1920     llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset);
1921 
1922     llvm::Constant *offset_array[1];
1923 
1924     offset_array[0] = offset_int;
1925 
1926     llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
1927     llvm::Type *char_type = llvm::Type::getInt8Ty(m_module->getContext());
1928     llvm::Type *char_pointer_type = char_type->getPointerTo();
1929 
1930     llvm::Constant *reloc_placeholder_bitcast = ConstantExpr::getBitCast(m_reloc_placeholder, char_pointer_type);
1931     llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(char_type, reloc_placeholder_bitcast, offsets);
1932     llvm::Constant *reloc_bitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
1933 
1934     return reloc_bitcast;
1935 }
1936 
1937 bool
1938 IRForTarget::runOnModule (Module &llvm_module)
1939 {
1940     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1941 
1942     m_module = &llvm_module;
1943     m_target_data.reset(new DataLayout(m_module));
1944     m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(), m_target_data->getPointerSizeInBits());
1945 
1946     if (log)
1947     {
1948         std::string s;
1949         raw_string_ostream oss(s);
1950 
1951         m_module->print(oss, NULL);
1952 
1953         oss.flush();
1954 
1955         log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
1956     }
1957 
1958     Function *const main_function = m_func_name.IsEmpty() ? nullptr : m_module->getFunction(m_func_name.GetStringRef());
1959 
1960     if (!m_func_name.IsEmpty() && !main_function)
1961     {
1962         if (log)
1963             log->Printf("Couldn't find \"%s()\" in the module", m_func_name.AsCString());
1964 
1965         if (m_error_stream)
1966             m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module",
1967                                    m_func_name.AsCString());
1968 
1969         return false;
1970     }
1971 
1972     if (main_function)
1973     {
1974         if (!FixFunctionLinkage(*main_function))
1975         {
1976             if (log)
1977                 log->Printf("Couldn't fix the linkage for the function");
1978 
1979             return false;
1980         }
1981     }
1982 
1983     llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext());
1984 
1985     m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
1986                                                    int8_ty,
1987                                                    false /* IsConstant */,
1988                                                    GlobalVariable::InternalLinkage,
1989                                                    Constant::getNullValue(int8_ty),
1990                                                    "reloc_placeholder",
1991                                                    NULL /* InsertBefore */,
1992                                                    GlobalVariable::NotThreadLocal /* ThreadLocal */,
1993                                                    0 /* AddressSpace */);
1994 
1995     ////////////////////////////////////////////////////////////
1996     // Replace $__lldb_expr_result with a persistent variable
1997     //
1998 
1999     if (main_function)
2000     {
2001         if (!CreateResultVariable(*main_function))
2002         {
2003             if (log)
2004                 log->Printf("CreateResultVariable() failed");
2005 
2006             // CreateResultVariable() reports its own errors, so we don't do so here
2007 
2008             return false;
2009         }
2010     }
2011 
2012     if (log && log->GetVerbose())
2013     {
2014         std::string s;
2015         raw_string_ostream oss(s);
2016 
2017         m_module->print(oss, NULL);
2018 
2019         oss.flush();
2020 
2021         log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2022     }
2023 
2024     for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2025          fi != fe;
2026          ++fi)
2027     {
2028         llvm::Function *function = &*fi;
2029 
2030         if (function->begin() == function->end())
2031             continue;
2032 
2033         Function::iterator bbi;
2034 
2035         for (bbi = function->begin();
2036              bbi != function->end();
2037              ++bbi)
2038         {
2039             if (!RemoveGuards(*bbi))
2040             {
2041                 if (log)
2042                     log->Printf("RemoveGuards() failed");
2043 
2044                 // RemoveGuards() reports its own errors, so we don't do so here
2045 
2046                 return false;
2047             }
2048 
2049             if (!RewritePersistentAllocs(*bbi))
2050             {
2051                 if (log)
2052                     log->Printf("RewritePersistentAllocs() failed");
2053 
2054                 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2055 
2056                 return false;
2057             }
2058 
2059             if (!RemoveCXAAtExit(*bbi))
2060             {
2061                 if (log)
2062                     log->Printf("RemoveCXAAtExit() failed");
2063 
2064                 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2065 
2066                 return false;
2067             }
2068         }
2069     }
2070 
2071     ///////////////////////////////////////////////////////////////////////////////
2072     // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2073     //
2074 
2075     if (!RewriteObjCConstStrings())
2076     {
2077         if (log)
2078             log->Printf("RewriteObjCConstStrings() failed");
2079 
2080         // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2081 
2082         return false;
2083     }
2084 
2085     for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2086          fi != fe;
2087          ++fi)
2088     {
2089         llvm::Function *function = &*fi;
2090 
2091         for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2092              bbi != bbe;
2093              ++bbi)
2094         {
2095             if (!RewriteObjCSelectors(*bbi))
2096             {
2097                 if (log)
2098                     log->Printf("RewriteObjCSelectors() failed");
2099 
2100                 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2101 
2102                 return false;
2103             }
2104         }
2105     }
2106 
2107     for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2108          fi != fe;
2109          ++fi)
2110     {
2111         llvm::Function *function = &*fi;
2112 
2113         for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2114              bbi != bbe;
2115              ++bbi)
2116         {
2117             if (!ResolveCalls(*bbi))
2118             {
2119                 if (log)
2120                     log->Printf("ResolveCalls() failed");
2121 
2122                 // ResolveCalls() reports its own errors, so we don't do so here
2123 
2124                 return false;
2125             }
2126         }
2127     }
2128 
2129     ////////////////////////////////////////////////////////////////////////
2130     // Run function-level passes that only make sense on the main function
2131     //
2132 
2133     if (main_function)
2134     {
2135         if (!ResolveExternals(*main_function))
2136         {
2137             if (log)
2138                 log->Printf("ResolveExternals() failed");
2139 
2140             // ResolveExternals() reports its own errors, so we don't do so here
2141 
2142             return false;
2143         }
2144 
2145         if (!ReplaceVariables(*main_function))
2146         {
2147             if (log)
2148                 log->Printf("ReplaceVariables() failed");
2149 
2150             // ReplaceVariables() reports its own errors, so we don't do so here
2151 
2152             return false;
2153         }
2154     }
2155 
2156     if (log && log->GetVerbose())
2157     {
2158         std::string s;
2159         raw_string_ostream oss(s);
2160 
2161         m_module->print(oss, NULL);
2162 
2163         oss.flush();
2164 
2165         log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
2166     }
2167 
2168     return true;
2169 }
2170 
2171 void
2172 IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
2173 {
2174 }
2175 
2176 PassManagerType
2177 IRForTarget::getPotentialPassManagerType() const
2178 {
2179     return PMT_ModulePassManager;
2180 }
2181