llvm.org GIT mirror llvm / 7e6d745
un-indent a huge amount of code out of an anonymous namespace. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@106500 91177308-0d34-0410-b5e6-96231b3b80d8 Chris Lattner 10 years ago
1 changed file(s) with 1812 addition(s) and 1814 deletion(s). Raw diff Collapse all Expand all
152152
153153 void printModuleBody();
154154 };
155
156 static unsigned indent_level = 0;
157 inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
158 Out << "\n";
159 if (delta >= 0 || indent_level >= unsigned(-delta))
160 indent_level += delta;
161 for (unsigned i = 0; i < indent_level; ++i)
162 Out << " ";
163 return Out;
164 }
165
166 inline void in() { indent_level++; }
167 inline void out() { if (indent_level >0) indent_level--; }
168
169 inline void
170 sanitize(std::string& str) {
171 for (size_t i = 0; i < str.length(); ++i)
172 if (!isalnum(str[i]) && str[i] != '_')
173 str[i] = '_';
174 }
175
176 inline std::string
177 getTypePrefix(const Type* Ty ) {
155 } // end anonymous namespace.
156
157 // FIXME: Shouldn't be using globals for this.
158 static unsigned indent_level = 0;
159 static formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0) {
160 Out << "\n";
161 if (delta >= 0 || indent_level >= unsigned(-delta))
162 indent_level += delta;
163 for (unsigned i = 0; i < indent_level; ++i)
164 Out << " ";
165 return Out;
166 }
167
168 static inline void in() { indent_level++; }
169 static inline void out() { if (indent_level >0) indent_level--; }
170
171 static inline void sanitize(std::string &str) {
172 for (size_t i = 0; i < str.length(); ++i)
173 if (!isalnum(str[i]) && str[i] != '_')
174 str[i] = '_';
175 }
176
177 static std::string getTypePrefix(const Type *Ty) {
178 switch (Ty->getTypeID()) {
179 case Type::VoidTyID: return "void_";
180 case Type::IntegerTyID:
181 return "int" + utostr(cast(Ty)->getBitWidth()) + "_";
182 case Type::FloatTyID: return "float_";
183 case Type::DoubleTyID: return "double_";
184 case Type::LabelTyID: return "label_";
185 case Type::FunctionTyID: return "func_";
186 case Type::StructTyID: return "struct_";
187 case Type::ArrayTyID: return "array_";
188 case Type::PointerTyID: return "ptr_";
189 case Type::VectorTyID: return "packed_";
190 case Type::OpaqueTyID: return "opaque_";
191 default: return "other_";
192 }
193 return "unknown_";
194 }
195
196 // Looks up the type in the symbol table and returns a pointer to its name or
197 // a null pointer if it wasn't found. Note that this isn't the same as the
198 // Mode::getTypeName function which will return an empty string, not a null
199 // pointer if the name is not found.
200 static const std::string *
201 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
202 TypeSymbolTable::const_iterator TI = ST.begin();
203 TypeSymbolTable::const_iterator TE = ST.end();
204 for (;TI != TE; ++TI)
205 if (TI->second == Ty)
206 return &(TI->first);
207 return 0;
208 }
209
210 void CppWriter::error(const std::string& msg) {
211 report_fatal_error(msg);
212 }
213
214 // printCFP - Print a floating point constant .. very carefully :)
215 // This makes sure that conversion to/from floating yields the same binary
216 // result so that we don't lose precision.
217 void CppWriter::printCFP(const ConstantFP *CFP) {
218 bool ignored;
219 APFloat APF = APFloat(CFP->getValueAPF()); // copy
220 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
221 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
222 Out << "ConstantFP::get(mod->getContext(), ";
223 Out << "APFloat(";
224 #if HAVE_PRINTF_A
225 char Buffer[100];
226 sprintf(Buffer, "%A", APF.convertToDouble());
227 if ((!strncmp(Buffer, "0x", 2) ||
228 !strncmp(Buffer, "-0x", 3) ||
229 !strncmp(Buffer, "+0x", 3)) &&
230 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
231 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
232 Out << "BitsToDouble(" << Buffer << ")";
233 else
234 Out << "BitsToFloat((float)" << Buffer << ")";
235 Out << ")";
236 } else {
237 #endif
238 std::string StrVal = ftostr(CFP->getValueAPF());
239
240 while (StrVal[0] == ' ')
241 StrVal.erase(StrVal.begin());
242
243 // Check to make sure that the stringized number is not some string like
244 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
245 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
246 ((StrVal[0] == '-' || StrVal[0] == '+') &&
247 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
248 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
249 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
250 Out << StrVal;
251 else
252 Out << StrVal << "f";
253 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
254 Out << "BitsToDouble(0x"
255 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
256 << "ULL) /* " << StrVal << " */";
257 else
258 Out << "BitsToFloat(0x"
259 << utohexstr((uint32_t)CFP->getValueAPF().
260 bitcastToAPInt().getZExtValue())
261 << "U) /* " << StrVal << " */";
262 Out << ")";
263 #if HAVE_PRINTF_A
264 }
265 #endif
266 Out << ")";
267 }
268
269 void CppWriter::printCallingConv(CallingConv::ID cc){
270 // Print the calling convention.
271 switch (cc) {
272 case CallingConv::C: Out << "CallingConv::C"; break;
273 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
274 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
275 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
276 default: Out << cc; break;
277 }
278 }
279
280 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
281 switch (LT) {
282 case GlobalValue::InternalLinkage:
283 Out << "GlobalValue::InternalLinkage"; break;
284 case GlobalValue::PrivateLinkage:
285 Out << "GlobalValue::PrivateLinkage"; break;
286 case GlobalValue::LinkerPrivateLinkage:
287 Out << "GlobalValue::LinkerPrivateLinkage"; break;
288 case GlobalValue::AvailableExternallyLinkage:
289 Out << "GlobalValue::AvailableExternallyLinkage "; break;
290 case GlobalValue::LinkOnceAnyLinkage:
291 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
292 case GlobalValue::LinkOnceODRLinkage:
293 Out << "GlobalValue::LinkOnceODRLinkage "; break;
294 case GlobalValue::WeakAnyLinkage:
295 Out << "GlobalValue::WeakAnyLinkage"; break;
296 case GlobalValue::WeakODRLinkage:
297 Out << "GlobalValue::WeakODRLinkage"; break;
298 case GlobalValue::AppendingLinkage:
299 Out << "GlobalValue::AppendingLinkage"; break;
300 case GlobalValue::ExternalLinkage:
301 Out << "GlobalValue::ExternalLinkage"; break;
302 case GlobalValue::DLLImportLinkage:
303 Out << "GlobalValue::DLLImportLinkage"; break;
304 case GlobalValue::DLLExportLinkage:
305 Out << "GlobalValue::DLLExportLinkage"; break;
306 case GlobalValue::ExternalWeakLinkage:
307 Out << "GlobalValue::ExternalWeakLinkage"; break;
308 case GlobalValue::CommonLinkage:
309 Out << "GlobalValue::CommonLinkage"; break;
310 }
311 }
312
313 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
314 switch (VisType) {
315 default: llvm_unreachable("Unknown GVar visibility");
316 case GlobalValue::DefaultVisibility:
317 Out << "GlobalValue::DefaultVisibility";
318 break;
319 case GlobalValue::HiddenVisibility:
320 Out << "GlobalValue::HiddenVisibility";
321 break;
322 case GlobalValue::ProtectedVisibility:
323 Out << "GlobalValue::ProtectedVisibility";
324 break;
325 }
326 }
327
328 // printEscapedString - Print each character of the specified string, escaping
329 // it if it is not printable or if it is an escape char.
330 void CppWriter::printEscapedString(const std::string &Str) {
331 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
332 unsigned char C = Str[i];
333 if (isprint(C) && C != '"' && C != '\\') {
334 Out << C;
335 } else {
336 Out << "\\x"
337 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
338 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
339 }
340 }
341 }
342
343 std::string CppWriter::getCppName(const Type* Ty) {
344 // First, handle the primitive types .. easy
345 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
178346 switch (Ty->getTypeID()) {
179 case Type::VoidTyID: return "void_";
180 case Type::IntegerTyID:
181 return std::string("int") + utostr(cast(Ty)->getBitWidth()) +
182 "_";
183 case Type::FloatTyID: return "float_";
184 case Type::DoubleTyID: return "double_";
185 case Type::LabelTyID: return "label_";
186 case Type::FunctionTyID: return "func_";
187 case Type::StructTyID: return "struct_";
188 case Type::ArrayTyID: return "array_";
189 case Type::PointerTyID: return "ptr_";
190 case Type::VectorTyID: return "packed_";
191 case Type::OpaqueTyID: return "opaque_";
192 default: return "other_";
193 }
194 return "unknown_";
195 }
196
197 // Looks up the type in the symbol table and returns a pointer to its name or
198 // a null pointer if it wasn't found. Note that this isn't the same as the
199 // Mode::getTypeName function which will return an empty string, not a null
200 // pointer if the name is not found.
201 inline const std::string*
202 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
203 TypeSymbolTable::const_iterator TI = ST.begin();
204 TypeSymbolTable::const_iterator TE = ST.end();
205 for (;TI != TE; ++TI)
206 if (TI->second == Ty)
207 return &(TI->first);
208 return 0;
209 }
210
211 void CppWriter::error(const std::string& msg) {
212 report_fatal_error(msg);
213 }
214
215 // printCFP - Print a floating point constant .. very carefully :)
216 // This makes sure that conversion to/from floating yields the same binary
217 // result so that we don't lose precision.
218 void CppWriter::printCFP(const ConstantFP *CFP) {
219 bool ignored;
220 APFloat APF = APFloat(CFP->getValueAPF()); // copy
221 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
222 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
223 Out << "ConstantFP::get(mod->getContext(), ";
224 Out << "APFloat(";
225 #if HAVE_PRINTF_A
226 char Buffer[100];
227 sprintf(Buffer, "%A", APF.convertToDouble());
228 if ((!strncmp(Buffer, "0x", 2) ||
229 !strncmp(Buffer, "-0x", 3) ||
230 !strncmp(Buffer, "+0x", 3)) &&
231 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
232 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
233 Out << "BitsToDouble(" << Buffer << ")";
347 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
348 case Type::IntegerTyID: {
349 unsigned BitWidth = cast(Ty)->getBitWidth();
350 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
351 }
352 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
353 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
354 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
355 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
356 default:
357 error("Invalid primitive type");
358 break;
359 }
360 // shouldn't be returned, but make it sensible
361 return "Type::getVoidTy(mod->getContext())";
362 }
363
364 // Now, see if we've seen the type before and return that
365 TypeMap::iterator I = TypeNames.find(Ty);
366 if (I != TypeNames.end())
367 return I->second;
368
369 // Okay, let's build a new name for this type. Start with a prefix
370 const char* prefix = 0;
371 switch (Ty->getTypeID()) {
372 case Type::FunctionTyID: prefix = "FuncTy_"; break;
373 case Type::StructTyID: prefix = "StructTy_"; break;
374 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
375 case Type::PointerTyID: prefix = "PointerTy_"; break;
376 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
377 case Type::VectorTyID: prefix = "VectorTy_"; break;
378 default: prefix = "OtherTy_"; break; // prevent breakage
379 }
380
381 // See if the type has a name in the symboltable and build accordingly
382 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
383 std::string name;
384 if (tName)
385 name = std::string(prefix) + *tName;
386 else
387 name = std::string(prefix) + utostr(uniqueNum++);
388 sanitize(name);
389
390 // Save the name
391 return TypeNames[Ty] = name;
392 }
393
394 void CppWriter::printCppName(const Type* Ty) {
395 printEscapedString(getCppName(Ty));
396 }
397
398 std::string CppWriter::getCppName(const Value* val) {
399 std::string name;
400 ValueMap::iterator I = ValueNames.find(val);
401 if (I != ValueNames.end() && I->first == val)
402 return I->second;
403
404 if (const GlobalVariable* GV = dyn_cast(val)) {
405 name = std::string("gvar_") +
406 getTypePrefix(GV->getType()->getElementType());
407 } else if (isa(val)) {
408 name = std::string("func_");
409 } else if (const Constant* C = dyn_cast(val)) {
410 name = std::string("const_") + getTypePrefix(C->getType());
411 } else if (const Argument* Arg = dyn_cast(val)) {
412 if (is_inline) {
413 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
414 Function::const_arg_iterator(Arg)) + 1;
415 name = std::string("arg_") + utostr(argNum);
416 NameSet::iterator NI = UsedNames.find(name);
417 if (NI != UsedNames.end())
418 name += std::string("_") + utostr(uniqueNum++);
419 UsedNames.insert(name);
420 return ValueNames[val] = name;
421 } else {
422 name = getTypePrefix(val->getType());
423 }
424 } else {
425 name = getTypePrefix(val->getType());
426 }
427 if (val->hasName())
428 name += val->getName();
429 else
430 name += utostr(uniqueNum++);
431 sanitize(name);
432 NameSet::iterator NI = UsedNames.find(name);
433 if (NI != UsedNames.end())
434 name += std::string("_") + utostr(uniqueNum++);
435 UsedNames.insert(name);
436 return ValueNames[val] = name;
437 }
438
439 void CppWriter::printCppName(const Value* val) {
440 printEscapedString(getCppName(val));
441 }
442
443 void CppWriter::printAttributes(const AttrListPtr &PAL,
444 const std::string &name) {
445 Out << "AttrListPtr " << name << "_PAL;";
446 nl(Out);
447 if (!PAL.isEmpty()) {
448 Out << '{'; in(); nl(Out);
449 Out << "SmallVector Attrs;"; nl(Out);
450 Out << "AttributeWithIndex PAWI;"; nl(Out);
451 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
452 unsigned index = PAL.getSlot(i).Index;
453 Attributes attrs = PAL.getSlot(i).Attrs;
454 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
455 #define HANDLE_ATTR(X) \
456 if (attrs & Attribute::X) \
457 Out << " | Attribute::" #X; \
458 attrs &= ~Attribute::X;
459
460 HANDLE_ATTR(SExt);
461 HANDLE_ATTR(ZExt);
462 HANDLE_ATTR(NoReturn);
463 HANDLE_ATTR(InReg);
464 HANDLE_ATTR(StructRet);
465 HANDLE_ATTR(NoUnwind);
466 HANDLE_ATTR(NoAlias);
467 HANDLE_ATTR(ByVal);
468 HANDLE_ATTR(Nest);
469 HANDLE_ATTR(ReadNone);
470 HANDLE_ATTR(ReadOnly);
471 HANDLE_ATTR(InlineHint);
472 HANDLE_ATTR(NoInline);
473 HANDLE_ATTR(AlwaysInline);
474 HANDLE_ATTR(OptimizeForSize);
475 HANDLE_ATTR(StackProtect);
476 HANDLE_ATTR(StackProtectReq);
477 HANDLE_ATTR(NoCapture);
478 #undef HANDLE_ATTR
479 assert(attrs == 0 && "Unhandled attribute!");
480 Out << ";";
481 nl(Out);
482 Out << "Attrs.push_back(PAWI);";
483 nl(Out);
484 }
485 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
486 nl(Out);
487 out(); nl(Out);
488 Out << '}'; nl(Out);
489 }
490 }
491
492 bool CppWriter::printTypeInternal(const Type* Ty) {
493 // We don't print definitions for primitive types
494 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
495 return false;
496
497 // If we already defined this type, we don't need to define it again.
498 if (DefinedTypes.find(Ty) != DefinedTypes.end())
499 return false;
500
501 // Everything below needs the name for the type so get it now.
502 std::string typeName(getCppName(Ty));
503
504 // Search the type stack for recursion. If we find it, then generate this
505 // as an OpaqueType, but make sure not to do this multiple times because
506 // the type could appear in multiple places on the stack. Once the opaque
507 // definition is issued, it must not be re-issued. Consequently we have to
508 // check the UnresolvedTypes list as well.
509 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
510 Ty);
511 if (TI != TypeStack.end()) {
512 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
513 if (I == UnresolvedTypes.end()) {
514 Out << "PATypeHolder " << typeName;
515 Out << "_fwd = OpaqueType::get(mod->getContext());";
516 nl(Out);
517 UnresolvedTypes[Ty] = typeName;
518 }
519 return true;
520 }
521
522 // We're going to print a derived type which, by definition, contains other
523 // types. So, push this one we're printing onto the type stack to assist with
524 // recursive definitions.
525 TypeStack.push_back(Ty);
526
527 // Print the type definition
528 switch (Ty->getTypeID()) {
529 case Type::FunctionTyID: {
530 const FunctionType* FT = cast(Ty);
531 Out << "std::vector" << typeName << "_args;";
532 nl(Out);
533 FunctionType::param_iterator PI = FT->param_begin();
534 FunctionType::param_iterator PE = FT->param_end();
535 for (; PI != PE; ++PI) {
536 const Type* argTy = static_cast(*PI);
537 bool isForward = printTypeInternal(argTy);
538 std::string argName(getCppName(argTy));
539 Out << typeName << "_args.push_back(" << argName;
540 if (isForward)
541 Out << "_fwd";
542 Out << ");";
543 nl(Out);
544 }
545 bool isForward = printTypeInternal(FT->getReturnType());
546 std::string retTypeName(getCppName(FT->getReturnType()));
547 Out << "FunctionType* " << typeName << " = FunctionType::get(";
548 in(); nl(Out) << "/*Result=*/" << retTypeName;
549 if (isForward)
550 Out << "_fwd";
551 Out << ",";
552 nl(Out) << "/*Params=*/" << typeName << "_args,";
553 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
554 out();
555 nl(Out);
556 break;
557 }
558 case Type::StructTyID: {
559 const StructType* ST = cast(Ty);
560 Out << "std::vector" << typeName << "_fields;";
561 nl(Out);
562 StructType::element_iterator EI = ST->element_begin();
563 StructType::element_iterator EE = ST->element_end();
564 for (; EI != EE; ++EI) {
565 const Type* fieldTy = static_cast(*EI);
566 bool isForward = printTypeInternal(fieldTy);
567 std::string fieldName(getCppName(fieldTy));
568 Out << typeName << "_fields.push_back(" << fieldName;
569 if (isForward)
570 Out << "_fwd";
571 Out << ");";
572 nl(Out);
573 }
574 Out << "StructType* " << typeName << " = StructType::get("
575 << "mod->getContext(), "
576 << typeName << "_fields, /*isPacked=*/"
577 << (ST->isPacked() ? "true" : "false") << ");";
578 nl(Out);
579 break;
580 }
581 case Type::ArrayTyID: {
582 const ArrayType* AT = cast(Ty);
583 const Type* ET = AT->getElementType();
584 bool isForward = printTypeInternal(ET);
585 std::string elemName(getCppName(ET));
586 Out << "ArrayType* " << typeName << " = ArrayType::get("
587 << elemName << (isForward ? "_fwd" : "")
588 << ", " << utostr(AT->getNumElements()) << ");";
589 nl(Out);
590 break;
591 }
592 case Type::PointerTyID: {
593 const PointerType* PT = cast(Ty);
594 const Type* ET = PT->getElementType();
595 bool isForward = printTypeInternal(ET);
596 std::string elemName(getCppName(ET));
597 Out << "PointerType* " << typeName << " = PointerType::get("
598 << elemName << (isForward ? "_fwd" : "")
599 << ", " << utostr(PT->getAddressSpace()) << ");";
600 nl(Out);
601 break;
602 }
603 case Type::VectorTyID: {
604 const VectorType* PT = cast(Ty);
605 const Type* ET = PT->getElementType();
606 bool isForward = printTypeInternal(ET);
607 std::string elemName(getCppName(ET));
608 Out << "VectorType* " << typeName << " = VectorType::get("
609 << elemName << (isForward ? "_fwd" : "")
610 << ", " << utostr(PT->getNumElements()) << ");";
611 nl(Out);
612 break;
613 }
614 case Type::OpaqueTyID: {
615 Out << "OpaqueType* " << typeName;
616 Out << " = OpaqueType::get(mod->getContext());";
617 nl(Out);
618 break;
619 }
620 default:
621 error("Invalid TypeID");
622 }
623
624 // If the type had a name, make sure we recreate it.
625 const std::string* progTypeName =
626 findTypeName(TheModule->getTypeSymbolTable(),Ty);
627 if (progTypeName) {
628 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
629 << typeName << ");";
630 nl(Out);
631 }
632
633 // Pop us off the type stack
634 TypeStack.pop_back();
635
636 // Indicate that this type is now defined.
637 DefinedTypes.insert(Ty);
638
639 // Early resolve as many unresolved types as possible. Search the unresolved
640 // types map for the type we just printed. Now that its definition is complete
641 // we can resolve any previous references to it. This prevents a cascade of
642 // unresolved types.
643 TypeMap::iterator I = UnresolvedTypes.find(Ty);
644 if (I != UnresolvedTypes.end()) {
645 Out << "cast(" << I->second
646 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
647 nl(Out);
648 Out << I->second << " = cast<";
649 switch (Ty->getTypeID()) {
650 case Type::FunctionTyID: Out << "FunctionType"; break;
651 case Type::ArrayTyID: Out << "ArrayType"; break;
652 case Type::StructTyID: Out << "StructType"; break;
653 case Type::VectorTyID: Out << "VectorType"; break;
654 case Type::PointerTyID: Out << "PointerType"; break;
655 case Type::OpaqueTyID: Out << "OpaqueType"; break;
656 default: Out << "NoSuchDerivedType"; break;
657 }
658 Out << ">(" << I->second << "_fwd.get());";
659 nl(Out); nl(Out);
660 UnresolvedTypes.erase(I);
661 }
662
663 // Finally, separate the type definition from other with a newline.
664 nl(Out);
665
666 // We weren't a recursive type
667 return false;
668 }
669
670 // Prints a type definition. Returns true if it could not resolve all the
671 // types in the definition but had to use a forward reference.
672 void CppWriter::printType(const Type* Ty) {
673 assert(TypeStack.empty());
674 TypeStack.clear();
675 printTypeInternal(Ty);
676 assert(TypeStack.empty());
677 }
678
679 void CppWriter::printTypes(const Module* M) {
680 // Walk the symbol table and print out all its types
681 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
682 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
683 TI != TE; ++TI) {
684
685 // For primitive types and types already defined, just add a name
686 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
687 if (TI->second->isIntegerTy() || TI->second->isPrimitiveType() ||
688 TNI != TypeNames.end()) {
689 Out << "mod->addTypeName(\"";
690 printEscapedString(TI->first);
691 Out << "\", " << getCppName(TI->second) << ");";
692 nl(Out);
693 // For everything else, define the type
694 } else {
695 printType(TI->second);
696 }
697 }
698
699 // Add all of the global variables to the value table...
700 for (Module::const_global_iterator I = TheModule->global_begin(),
701 E = TheModule->global_end(); I != E; ++I) {
702 if (I->hasInitializer())
703 printType(I->getInitializer()->getType());
704 printType(I->getType());
705 }
706
707 // Add all the functions to the table
708 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
709 FI != FE; ++FI) {
710 printType(FI->getReturnType());
711 printType(FI->getFunctionType());
712 // Add all the function arguments
713 for (Function::const_arg_iterator AI = FI->arg_begin(),
714 AE = FI->arg_end(); AI != AE; ++AI) {
715 printType(AI->getType());
716 }
717
718 // Add all of the basic blocks and instructions
719 for (Function::const_iterator BB = FI->begin(),
720 E = FI->end(); BB != E; ++BB) {
721 printType(BB->getType());
722 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
723 ++I) {
724 printType(I->getType());
725 for (unsigned i = 0; i < I->getNumOperands(); ++i)
726 printType(I->getOperand(i)->getType());
727 }
728 }
729 }
730 }
731
732
733 // printConstant - Print out a constant pool entry...
734 void CppWriter::printConstant(const Constant *CV) {
735 // First, if the constant is actually a GlobalValue (variable or function)
736 // or its already in the constant list then we've printed it already and we
737 // can just return.
738 if (isa(CV) || ValueNames.find(CV) != ValueNames.end())
739 return;
740
741 std::string constName(getCppName(CV));
742 std::string typeName(getCppName(CV->getType()));
743
744 if (isa(CV)) {
745 // Skip variables and functions, we emit them elsewhere
746 return;
747 }
748
749 if (const ConstantInt *CI = dyn_cast(CV)) {
750 std::string constValue = CI->getValue().toString(10, true);
751 Out << "ConstantInt* " << constName
752 << " = ConstantInt::get(mod->getContext(), APInt("
753 << cast(CI->getType())->getBitWidth()
754 << ", StringRef(\"" << constValue << "\"), 10));";
755 } else if (isa(CV)) {
756 Out << "ConstantAggregateZero* " << constName
757 << " = ConstantAggregateZero::get(" << typeName << ");";
758 } else if (isa(CV)) {
759 Out << "ConstantPointerNull* " << constName
760 << " = ConstantPointerNull::get(" << typeName << ");";
761 } else if (const ConstantFP *CFP = dyn_cast(CV)) {
762 Out << "ConstantFP* " << constName << " = ";
763 printCFP(CFP);
764 Out << ";";
765 } else if (const ConstantArray *CA = dyn_cast(CV)) {
766 if (CA->isString() &&
767 CA->getType()->getElementType() ==
768 Type::getInt8Ty(CA->getContext())) {
769 Out << "Constant* " << constName <<
770 " = ConstantArray::get(mod->getContext(), \"";
771 std::string tmp = CA->getAsString();
772 bool nullTerminate = false;
773 if (tmp[tmp.length()-1] == 0) {
774 tmp.erase(tmp.length()-1);
775 nullTerminate = true;
776 }
777 printEscapedString(tmp);
778 // Determine if we want null termination or not.
779 if (nullTerminate)
780 Out << "\", true"; // Indicate that the null terminator should be
781 // added.
234782 else
235 Out << "BitsToFloat((float)" << Buffer << ")";
236 Out << ")";
783 Out << "\", false";// No null terminator
784 Out << ");";
237785 } else {
238 #endif
239 std::string StrVal = ftostr(CFP->getValueAPF());
240
241 while (StrVal[0] == ' ')
242 StrVal.erase(StrVal.begin());
243
244 // Check to make sure that the stringized number is not some string like
245 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
246 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
247 ((StrVal[0] == '-' || StrVal[0] == '+') &&
248 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
249 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
250 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
251 Out << StrVal;
252 else
253 Out << StrVal << "f";
254 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
255 Out << "BitsToDouble(0x"
256 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
257 << "ULL) /* " << StrVal << " */";
258 else
259 Out << "BitsToFloat(0x"
260 << utohexstr((uint32_t)CFP->getValueAPF().
261 bitcastToAPInt().getZExtValue())
262 << "U) /* " << StrVal << " */";
263 Out << ")";
264 #if HAVE_PRINTF_A
265 }
266 #endif
267 Out << ")";
268 }
269
270 void CppWriter::printCallingConv(CallingConv::ID cc){
271 // Print the calling convention.
272 switch (cc) {
273 case CallingConv::C: Out << "CallingConv::C"; break;
274 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
275 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
276 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
277 default: Out << cc; break;
278 }
279 }
280
281 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
282 switch (LT) {
283 case GlobalValue::InternalLinkage:
284 Out << "GlobalValue::InternalLinkage"; break;
285 case GlobalValue::PrivateLinkage:
286 Out << "GlobalValue::PrivateLinkage"; break;
287 case GlobalValue::LinkerPrivateLinkage:
288 Out << "GlobalValue::LinkerPrivateLinkage"; break;
289 case GlobalValue::AvailableExternallyLinkage:
290 Out << "GlobalValue::AvailableExternallyLinkage "; break;
291 case GlobalValue::LinkOnceAnyLinkage:
292 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
293 case GlobalValue::LinkOnceODRLinkage:
294 Out << "GlobalValue::LinkOnceODRLinkage "; break;
295 case GlobalValue::WeakAnyLinkage:
296 Out << "GlobalValue::WeakAnyLinkage"; break;
297 case GlobalValue::WeakODRLinkage:
298 Out << "GlobalValue::WeakODRLinkage"; break;
299 case GlobalValue::AppendingLinkage:
300 Out << "GlobalValue::AppendingLinkage"; break;
301 case GlobalValue::ExternalLinkage:
302 Out << "GlobalValue::ExternalLinkage"; break;
303 case GlobalValue::DLLImportLinkage:
304 Out << "GlobalValue::DLLImportLinkage"; break;
305 case GlobalValue::DLLExportLinkage:
306 Out << "GlobalValue::DLLExportLinkage"; break;
307 case GlobalValue::ExternalWeakLinkage:
308 Out << "GlobalValue::ExternalWeakLinkage"; break;
309 case GlobalValue::CommonLinkage:
310 Out << "GlobalValue::CommonLinkage"; break;
311 }
312 }
313
314 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
315 switch (VisType) {
316 default: llvm_unreachable("Unknown GVar visibility");
317 case GlobalValue::DefaultVisibility:
318 Out << "GlobalValue::DefaultVisibility";
319 break;
320 case GlobalValue::HiddenVisibility:
321 Out << "GlobalValue::HiddenVisibility";
322 break;
323 case GlobalValue::ProtectedVisibility:
324 Out << "GlobalValue::ProtectedVisibility";
325 break;
326 }
327 }
328
329 // printEscapedString - Print each character of the specified string, escaping
330 // it if it is not printable or if it is an escape char.
331 void CppWriter::printEscapedString(const std::string &Str) {
332 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
333 unsigned char C = Str[i];
334 if (isprint(C) && C != '"' && C != '\\') {
335 Out << C;
336 } else {
337 Out << "\\x"
338 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
339 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
786 Out << "std::vector " << constName << "_elems;";
787 nl(Out);
788 unsigned N = CA->getNumOperands();
789 for (unsigned i = 0; i < N; ++i) {
790 printConstant(CA->getOperand(i)); // recurse to print operands
791 Out << constName << "_elems.push_back("
792 << getCppName(CA->getOperand(i)) << ");";
793 nl(Out);
340794 }
341 }
342 }
343
344 std::string CppWriter::getCppName(const Type* Ty) {
345 // First, handle the primitive types .. easy
346 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
347 switch (Ty->getTypeID()) {
348 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
349 case Type::IntegerTyID: {
350 unsigned BitWidth = cast(Ty)->getBitWidth();
351 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
795 Out << "Constant* " << constName << " = ConstantArray::get("
796 << typeName << ", " << constName << "_elems);";
797 }
798 } else if (const ConstantStruct *CS = dyn_cast(CV)) {
799 Out << "std::vector " << constName << "_fields;";
800 nl(Out);
801 unsigned N = CS->getNumOperands();
802 for (unsigned i = 0; i < N; i++) {
803 printConstant(CS->getOperand(i));
804 Out << constName << "_fields.push_back("
805 << getCppName(CS->getOperand(i)) << ");";
806 nl(Out);
807 }
808 Out << "Constant* " << constName << " = ConstantStruct::get("
809 << typeName << ", " << constName << "_fields);";
810 } else if (const ConstantVector *CP = dyn_cast(CV)) {
811 Out << "std::vector " << constName << "_elems;";
812 nl(Out);
813 unsigned N = CP->getNumOperands();
814 for (unsigned i = 0; i < N; ++i) {
815 printConstant(CP->getOperand(i));
816 Out << constName << "_elems.push_back("
817 << getCppName(CP->getOperand(i)) << ");";
818 nl(Out);
819 }
820 Out << "Constant* " << constName << " = ConstantVector::get("
821 << typeName << ", " << constName << "_elems);";
822 } else if (isa(CV)) {
823 Out << "UndefValue* " << constName << " = UndefValue::get("
824 << typeName << ");";
825 } else if (const ConstantExpr *CE = dyn_cast(CV)) {
826 if (CE->getOpcode() == Instruction::GetElementPtr) {
827 Out << "std::vector " << constName << "_indices;";
828 nl(Out);
829 printConstant(CE->getOperand(0));
830 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
831 printConstant(CE->getOperand(i));
832 Out << constName << "_indices.push_back("
833 << getCppName(CE->getOperand(i)) << ");";
834 nl(Out);
352835 }
353 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
354 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
355 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
356 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
836 Out << "Constant* " << constName
837 << " = ConstantExpr::getGetElementPtr("
838 << getCppName(CE->getOperand(0)) << ", "
839 << "&" << constName << "_indices[0], "
840 << constName << "_indices.size()"
841 << ");";
842 } else if (CE->isCast()) {
843 printConstant(CE->getOperand(0));
844 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
845 switch (CE->getOpcode()) {
846 default: llvm_unreachable("Invalid cast opcode");
847 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
848 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
849 case Instruction::SExt: Out << "Instruction::SExt"; break;
850 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
851 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
852 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
853 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
854 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
855 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
856 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
857 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
858 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
859 }
860 Out << ", " << getCppName(CE->getOperand(0)) << ", "
861 << getCppName(CE->getType()) << ");";
862 } else {
863 unsigned N = CE->getNumOperands();
864 for (unsigned i = 0; i < N; ++i ) {
865 printConstant(CE->getOperand(i));
866 }
867 Out << "Constant* " << constName << " = ConstantExpr::";
868 switch (CE->getOpcode()) {
869 case Instruction::Add: Out << "getAdd("; break;
870 case Instruction::FAdd: Out << "getFAdd("; break;
871 case Instruction::Sub: Out << "getSub("; break;
872 case Instruction::FSub: Out << "getFSub("; break;
873 case Instruction::Mul: Out << "getMul("; break;
874 case Instruction::FMul: Out << "getFMul("; break;
875 case Instruction::UDiv: Out << "getUDiv("; break;
876 case Instruction::SDiv: Out << "getSDiv("; break;
877 case Instruction::FDiv: Out << "getFDiv("; break;
878 case Instruction::URem: Out << "getURem("; break;
879 case Instruction::SRem: Out << "getSRem("; break;
880 case Instruction::FRem: Out << "getFRem("; break;
881 case Instruction::And: Out << "getAnd("; break;
882 case Instruction::Or: Out << "getOr("; break;
883 case Instruction::Xor: Out << "getXor("; break;
884 case Instruction::ICmp:
885 Out << "getICmp(ICmpInst::ICMP_";
886 switch (CE->getPredicate()) {
887 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
888 case ICmpInst::ICMP_NE: Out << "NE"; break;
889 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
890 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
891 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
892 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
893 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
894 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
895 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
896 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
897 default: error("Invalid ICmp Predicate");
898 }
899 break;
900 case Instruction::FCmp:
901 Out << "getFCmp(FCmpInst::FCMP_";
902 switch (CE->getPredicate()) {
903 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
904 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
905 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
906 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
907 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
908 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
909 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
910 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
911 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
912 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
913 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
914 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
915 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
916 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
917 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
918 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
919 default: error("Invalid FCmp Predicate");
920 }
921 break;
922 case Instruction::Shl: Out << "getShl("; break;
923 case Instruction::LShr: Out << "getLShr("; break;
924 case Instruction::AShr: Out << "getAShr("; break;
925 case Instruction::Select: Out << "getSelect("; break;
926 case Instruction::ExtractElement: Out << "getExtractElement("; break;
927 case Instruction::InsertElement: Out << "getInsertElement("; break;
928 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
357929 default:
358 error("Invalid primitive type");
930 error("Invalid constant expression");
359931 break;
360932 }
361 // shouldn't be returned, but make it sensible
362 return "Type::getVoidTy(mod->getContext())";
363 }
364
365 // Now, see if we've seen the type before and return that
366 TypeMap::iterator I = TypeNames.find(Ty);
367 if (I != TypeNames.end())
368 return I->second;
369
370 // Okay, let's build a new name for this type. Start with a prefix
371 const char* prefix = 0;
372 switch (Ty->getTypeID()) {
373 case Type::FunctionTyID: prefix = "FuncTy_"; break;
374 case Type::StructTyID: prefix = "StructTy_"; break;
375 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
376 case Type::PointerTyID: prefix = "PointerTy_"; break;
377 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
378 case Type::VectorTyID: prefix = "VectorTy_"; break;
379 default: prefix = "OtherTy_"; break; // prevent breakage
380 }
381
382 // See if the type has a name in the symboltable and build accordingly
383 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
384 std::string name;
385 if (tName)
386 name = std::string(prefix) + *tName;
387 else
388 name = std::string(prefix) + utostr(uniqueNum++);
389 sanitize(name);
390
391 // Save the name
392 return TypeNames[Ty] = name;
393 }
394
395 void CppWriter::printCppName(const Type* Ty) {
396 printEscapedString(getCppName(Ty));
397 }
398
399 std::string CppWriter::getCppName(const Value* val) {
400 std::string name;
401 ValueMap::iterator I = ValueNames.find(val);
402 if (I != ValueNames.end() && I->first == val)
403 return I->second;
404
405 if (const GlobalVariable* GV = dyn_cast(val)) {
406 name = std::string("gvar_") +
407 getTypePrefix(GV->getType()->getElementType());
408 } else if (isa(val)) {
409 name = std::string("func_");
410 } else if (const Constant* C = dyn_cast(val)) {
411 name = std::string("const_") + getTypePrefix(C->getType());
412 } else if (const Argument* Arg = dyn_cast(val)) {
413 if (is_inline) {
414 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
415 Function::const_arg_iterator(Arg)) + 1;
416 name = std::string("arg_") + utostr(argNum);
417 NameSet::iterator NI = UsedNames.find(name);
418 if (NI != UsedNames.end())
419 name += std::string("_") + utostr(uniqueNum++);
420 UsedNames.insert(name);
421 return ValueNames[val] = name;
422 } else {
423 name = getTypePrefix(val->getType());
424 }
425 } else {
426 name = getTypePrefix(val->getType());
427 }
428 if (val->hasName())
429 name += val->getName();
430 else
431 name += utostr(uniqueNum++);
432 sanitize(name);
433 NameSet::iterator NI = UsedNames.find(name);
434 if (NI != UsedNames.end())
435 name += std::string("_") + utostr(uniqueNum++);
436 UsedNames.insert(name);
437 return ValueNames[val] = name;
438 }
439
440 void CppWriter::printCppName(const Value* val) {
441 printEscapedString(getCppName(val));
442 }
443
444 void CppWriter::printAttributes(const AttrListPtr &PAL,
445 const std::string &name) {
446 Out << "AttrListPtr " << name << "_PAL;";
447 nl(Out);
448 if (!PAL.isEmpty()) {
449 Out << '{'; in(); nl(Out);
450 Out << "SmallVector Attrs;"; nl(Out);
451 Out << "AttributeWithIndex PAWI;"; nl(Out);
452 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
453 unsigned index = PAL.getSlot(i).Index;
454 Attributes attrs = PAL.getSlot(i).Attrs;
455 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
456 #define HANDLE_ATTR(X) \
457 if (attrs & Attribute::X) \
458 Out << " | Attribute::" #X; \
459 attrs &= ~Attribute::X;
460
461 HANDLE_ATTR(SExt);
462 HANDLE_ATTR(ZExt);
463 HANDLE_ATTR(NoReturn);
464 HANDLE_ATTR(InReg);
465 HANDLE_ATTR(StructRet);
466 HANDLE_ATTR(NoUnwind);
467 HANDLE_ATTR(NoAlias);
468 HANDLE_ATTR(ByVal);
469 HANDLE_ATTR(Nest);
470 HANDLE_ATTR(ReadNone);
471 HANDLE_ATTR(ReadOnly);
472 HANDLE_ATTR(InlineHint);
473 HANDLE_ATTR(NoInline);
474 HANDLE_ATTR(AlwaysInline);
475 HANDLE_ATTR(OptimizeForSize);
476 HANDLE_ATTR(StackProtect);
477 HANDLE_ATTR(StackProtectReq);
478 HANDLE_ATTR(NoCapture);
479 #undef HANDLE_ATTR
480 assert(attrs == 0 && "Unhandled attribute!");
481 Out << ";";
482 nl(Out);
483 Out << "Attrs.push_back(PAWI);";
484 nl(Out);
485 }
486 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
487 nl(Out);
488 out(); nl(Out);
489 Out << '}'; nl(Out);
490 }
491 }
492
493 bool CppWriter::printTypeInternal(const Type* Ty) {
494 // We don't print definitions for primitive types
495 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
496 return false;
497
498 // If we already defined this type, we don't need to define it again.
499 if (DefinedTypes.find(Ty) != DefinedTypes.end())
500 return false;
501
502 // Everything below needs the name for the type so get it now.
503 std::string typeName(getCppName(Ty));
504
505 // Search the type stack for recursion. If we find it, then generate this
506 // as an OpaqueType, but make sure not to do this multiple times because
507 // the type could appear in multiple places on the stack. Once the opaque
508 // definition is issued, it must not be re-issued. Consequently we have to
509 // check the UnresolvedTypes list as well.
510 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
511 Ty);
512 if (TI != TypeStack.end()) {
513 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
514 if (I == UnresolvedTypes.end()) {
515 Out << "PATypeHolder " << typeName;
516 Out << "_fwd = OpaqueType::get(mod->getContext());";
517 nl(Out);
518 UnresolvedTypes[Ty] = typeName;
519 }
520 return true;
521 }
522
523 // We're going to print a derived type which, by definition, contains other
524 // types. So, push this one we're printing onto the type stack to assist with
525 // recursive definitions.
526 TypeStack.push_back(Ty);
527
528 // Print the type definition
529 switch (Ty->getTypeID()) {
530 case Type::FunctionTyID: {
531 const FunctionType* FT = cast(Ty);
532 Out << "std::vector" << typeName << "_args;";
533 nl(Out);
534 FunctionType::param_iterator PI = FT->param_begin();
535 FunctionType::param_iterator PE = FT->param_end();
536 for (; PI != PE; ++PI) {
537 const Type* argTy = static_cast(*PI);
538 bool isForward = printTypeInternal(argTy);
539 std::string argName(getCppName(argTy));
540 Out << typeName << "_args.push_back(" << argName;
541 if (isForward)
542 Out << "_fwd";
543 Out << ");";
544 nl(Out);
545 }
546 bool isForward = printTypeInternal(FT->getReturnType());
547 std::string retTypeName(getCppName(FT->getReturnType()));
548 Out << "FunctionType* " << typeName << " = FunctionType::get(";
549 in(); nl(Out) << "/*Result=*/" << retTypeName;
550 if (isForward)
551 Out << "_fwd";
552 Out << ",";
553 nl(Out) << "/*Params=*/" << typeName << "_args,";
554 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
555 out();
556 nl(Out);
557 break;
558 }
559 case Type::StructTyID: {
560 const StructType* ST = cast(Ty);
561 Out << "std::vector" << typeName << "_fields;";
562 nl(Out);
563 StructType::element_iterator EI = ST->element_begin();
564 StructType::element_iterator EE = ST->element_end();
565 for (; EI != EE; ++EI) {
566 const Type* fieldTy = static_cast(*EI);
567 bool isForward = printTypeInternal(fieldTy);
568 std::string fieldName(getCppName(fieldTy));
569 Out << typeName << "_fields.push_back(" << fieldName;
570 if (isForward)
571 Out << "_fwd";
572 Out << ");";
573 nl(Out);
574 }
575 Out << "StructType* " << typeName << " = StructType::get("
576 << "mod->getContext(), "
577 << typeName << "_fields, /*isPacked=*/"
578 << (ST->isPacked() ? "true" : "false") << ");";
579 nl(Out);
580 break;
581 }
582 case Type::ArrayTyID: {
583 const ArrayType* AT = cast(Ty);
584 const Type* ET = AT->getElementType();
585 bool isForward = printTypeInternal(ET);
586 std::string elemName(getCppName(ET));
587 Out << "ArrayType* " << typeName << " = ArrayType::get("
588 << elemName << (isForward ? "_fwd" : "")
589 << ", " << utostr(AT->getNumElements()) << ");";
590 nl(Out);
591 break;
592 }
593 case Type::PointerTyID: {
594 const PointerType* PT = cast(Ty);
595 const Type* ET = PT->getElementType();
596 bool isForward = printTypeInternal(ET);
597 std::string elemName(getCppName(ET));
598 Out << "PointerType* " << typeName << " = PointerType::get("
599 << elemName << (isForward ? "_fwd" : "")
600 << ", " << utostr(PT->getAddressSpace()) << ");";
601 nl(Out);
602 break;
603 }
604 case Type::VectorTyID: {
605 const VectorType* PT = cast(Ty);
606 const Type* ET = PT->getElementType();
607 bool isForward = printTypeInternal(ET);
608 std::string elemName(getCppName(ET));
609 Out << "VectorType* " << typeName << " = VectorType::get("
610 << elemName << (isForward ? "_fwd" : "")
611 << ", " << utostr(PT->getNumElements()) << ");";
612 nl(Out);
613 break;
614 }
615 case Type::OpaqueTyID: {
616 Out << "OpaqueType* " << typeName;
617 Out << " = OpaqueType::get(mod->getContext());";
618 nl(Out);
619 break;
620 }
621 default:
622 error("Invalid TypeID");
623 }
624
625 // If the type had a name, make sure we recreate it.
626 const std::string* progTypeName =
627 findTypeName(TheModule->getTypeSymbolTable(),Ty);
628 if (progTypeName) {
629 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
630 << typeName << ");";
631 nl(Out);
632 }
633
634 // Pop us off the type stack
635 TypeStack.pop_back();
636
637 // Indicate that this type is now defined.
638 DefinedTypes.insert(Ty);
639
640 // Early resolve as many unresolved types as possible. Search the unresolved
641 // types map for the type we just printed. Now that its definition is complete
642 // we can resolve any previous references to it. This prevents a cascade of
643 // unresolved types.
644 TypeMap::iterator I = UnresolvedTypes.find(Ty);
645 if (I != UnresolvedTypes.end()) {
646 Out << "cast(" << I->second
647 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
648 nl(Out);
649 Out << I->second << " = cast<";
650 switch (Ty->getTypeID()) {
651 case Type::FunctionTyID: Out << "FunctionType"; break;
652 case Type::ArrayTyID: Out << "ArrayType"; break;
653 case Type::StructTyID: Out << "StructType"; break;
654 case Type::VectorTyID: Out << "VectorType"; break;
655 case Type::PointerTyID: Out << "PointerType"; break;
656 case Type::OpaqueTyID: Out << "OpaqueType"; break;
657 default: Out << "NoSuchDerivedType"; break;
658 }
659 Out << ">(" << I->second << "_fwd.get());";
660 nl(Out); nl(Out);
661 UnresolvedTypes.erase(I);
662 }
663
664 // Finally, separate the type definition from other with a newline.
665 nl(Out);
666
667 // We weren't a recursive type
668 return false;
669 }
670
671 // Prints a type definition. Returns true if it could not resolve all the
672 // types in the definition but had to use a forward reference.
673 void CppWriter::printType(const Type* Ty) {
674 assert(TypeStack.empty());
675 TypeStack.clear();
676 printTypeInternal(Ty);
677 assert(TypeStack.empty());
678 }
679
680 void CppWriter::printTypes(const Module* M) {
681 // Walk the symbol table and print out all its types
682 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
683 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
684 TI != TE; ++TI) {
685
686 // For primitive types and types already defined, just add a name
687 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
688 if (TI->second->isIntegerTy() || TI->second->isPrimitiveType() ||
689 TNI != TypeNames.end()) {
690 Out << "mod->addTypeName(\"";
691 printEscapedString(TI->first);
692 Out << "\", " << getCppName(TI->second) << ");";
693 nl(Out);
694 // For everything else, define the type
695 } else {
696 printType(TI->second);
697 }
698 }
699
700 // Add all of the global variables to the value table...
701 for (Module::const_global_iterator I = TheModule->global_begin(),
702 E = TheModule->global_end(); I != E; ++I) {
703 if (I->hasInitializer())
704 printType(I->getInitializer()->getType());
705 printType(I->getType());
706 }
707
708 // Add all the functions to the table
709 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
710 FI != FE; ++FI) {
711 printType(FI->getReturnType());
712 printType(FI->getFunctionType());
713 // Add all the function arguments
714 for (Function::const_arg_iterator AI = FI->arg_begin(),
715 AE = FI->arg_end(); AI != AE; ++AI) {
716 printType(AI->getType());
717 }
718
719 // Add all of the basic blocks and instructions
720 for (Function::const_iterator BB = FI->begin(),
721 E = FI->end(); BB != E; ++BB) {
722 printType(BB->getType());
723 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
724 ++I) {
725 printType(I->getType());
726 for (unsigned i = 0; i < I->getNumOperands(); ++i)
727 printType(I->getOperand(i)->getType());
728 }
729 }
730 }
731 }
732
733
734 // printConstant - Print out a constant pool entry...
735 void CppWriter::printConstant(const Constant *CV) {
736 // First, if the constant is actually a GlobalValue (variable or function)
737 // or its already in the constant list then we've printed it already and we
738 // can just return.
739 if (isa(CV) || ValueNames.find(CV) != ValueNames.end())
740 return;
741
742 std::string constName(getCppName(CV));
743 std::string typeName(getCppName(CV->getType()));
744
745 if (isa(CV)) {
746 // Skip variables and functions, we emit them elsewhere
747 return;
748 }
749
750 if (const ConstantInt *CI = dyn_cast(CV)) {
751 std::string constValue = CI->getValue().toString(10, true);
752 Out << "ConstantInt* " << constName
753 << " = ConstantInt::get(mod->getContext(), APInt("
754 << cast(CI->getType())->getBitWidth()
755 << ", StringRef(\"" << constValue << "\"), 10));";
756 } else if (isa(CV)) {
757 Out << "ConstantAggregateZero* " << constName
758 << " = ConstantAggregateZero::get(" << typeName << ");";
759 } else if (isa(CV)) {
760 Out << "ConstantPointerNull* " << constName
761 << " = ConstantPointerNull::get(" << typeName << ");";
762 } else if (const ConstantFP *CFP = dyn_cast(CV)) {
763 Out << "ConstantFP* " << constName << " = ";
764 printCFP(CFP);
765 Out << ";";
766 } else if (const ConstantArray *CA = dyn_cast(CV)) {
767 if (CA->isString() &&
768 CA->getType()->getElementType() ==
769 Type::getInt8Ty(CA->getContext())) {
770 Out << "Constant* " << constName <<
771 " = ConstantArray::get(mod->getContext(), \"";
772 std::string tmp = CA->getAsString();
773 bool nullTerminate = false;
774 if (tmp[tmp.length()-1] == 0) {
775 tmp.erase(tmp.length()-1);
776 nullTerminate = true;
777 }
778 printEscapedString(tmp);
779 // Determine if we want null termination or not.
780 if (nullTerminate)
781 Out << "\", true"; // Indicate that the null terminator should be
782 // added.
783 else
784 Out << "\", false";// No null terminator
785 Out << ");";
786 } else {
787 Out << "std::vector " << constName << "_elems;";
788 nl(Out);
789 unsigned N = CA->getNumOperands();
790 for (unsigned i = 0; i < N; ++i) {
791 printConstant(CA->getOperand(i)); // recurse to print operands
792 Out << constName << "_elems.push_back("
793 << getCppName(CA->getOperand(i)) << ");";
794 nl(Out);
795 }
796 Out << "Constant* " << constName << " = ConstantArray::get("
797 << typeName << ", " << constName << "_elems);";
798 }
799 } else if (const ConstantStruct *CS = dyn_cast(CV)) {
800 Out << "std::vector " << constName << "_fields;";
801 nl(Out);
802 unsigned N = CS->getNumOperands();
803 for (unsigned i = 0; i < N; i++) {
804 printConstant(CS->getOperand(i));
805 Out << constName << "_fields.push_back("
806 << getCppName(CS->getOperand(i)) << ");";
807 nl(Out);
808 }
809 Out << "Constant* " << constName << " = ConstantStruct::get("
810 << typeName << ", " << constName << "_fields);";
811 } else if (const ConstantVector *CP = dyn_cast(CV)) {
812 Out << "std::vector " << constName << "_elems;";
813 nl(Out);
814 unsigned N = CP->getNumOperands();
815 for (unsigned i = 0; i < N; ++i) {
816 printConstant(CP->getOperand(i));
817 Out << constName << "_elems.push_back("
818 << getCppName(CP->getOperand(i)) << ");";
819 nl(Out);
820 }
821 Out << "Constant* " << constName << " = ConstantVector::get("
822 << typeName << ", " << constName << "_elems);";
823 } else if (isa(CV)) {
824 Out << "UndefValue* " << constName << " = UndefValue::get("
825 << typeName << ");";
826 } else if (const ConstantExpr *CE = dyn_cast(CV)) {
827 if (CE->getOpcode() == Instruction::GetElementPtr) {
828 Out << "std::vector " << constName << "_indices;";
829 nl(Out);
830 printConstant(CE->getOperand(0));
831 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
832 printConstant(CE->getOperand(i));
833 Out << constName << "_indices.push_back("
834 << getCppName(CE->getOperand(i)) << ");";
835 nl(Out);
836 }
837 Out << "Constant* " << constName
838 << " = ConstantExpr::getGetElementPtr("
839 << getCppName(CE->getOperand(0)) << ", "
840 << "&" << constName << "_indices[0], "
841 << constName << "_indices.size()"
842 << ");";
843 } else if (CE->isCast()) {
844 printConstant(CE->getOperand(0));
845 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
846 switch (CE->getOpcode()) {
847 default: llvm_unreachable("Invalid cast opcode");
848 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
849 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
850 case Instruction::SExt: Out << "Instruction::SExt"; break;
851 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
852 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
853 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
854 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
855 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
856 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
857 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
858 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
859 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
860 }
861 Out << ", " << getCppName(CE->getOperand(0)) << ", "
862 << getCppName(CE->getType()) << ");";
863 } else {
864 unsigned N = CE->getNumOperands();
865 for (unsigned i = 0; i < N; ++i ) {
866 printConstant(CE->getOperand(i));
867 }
868 Out << "Constant* " << constName << " = ConstantExpr::";
869 switch (CE->getOpcode()) {
870 case Instruction::Add: Out << "getAdd("; break;
871 case Instruction::FAdd: Out << "getFAdd("; break;
872 case Instruction::Sub: Out << "getSub("; break;
873 case Instruction::FSub: Out << "getFSub("; break;
874 case Instruction::Mul: Out << "getMul("; break;
875 case Instruction::FMul: Out << "getFMul("; break;
876 case Instruction::UDiv: Out << "getUDiv("; break;
877 case Instruction::SDiv: Out << "getSDiv("; break;
878 case Instruction::FDiv: Out << "getFDiv("; break;
879 case Instruction::URem: Out << "getURem("; break;
880 case Instruction::SRem: Out << "getSRem("; break;
881 case Instruction::FRem: Out << "getFRem("; break;
882 case Instruction::And: Out << "getAnd("; break;
883 case Instruction::Or: Out << "getOr("; break;
884 case Instruction::Xor: Out << "getXor("; break;
885 case Instruction::ICmp:
886 Out << "getICmp(ICmpInst::ICMP_";
887 switch (CE->getPredicate()) {
888 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
889 case ICmpInst::ICMP_NE: Out << "NE"; break;
890 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
891 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
892 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
893 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
894 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
895 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
896 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
897 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
898 default: error("Invalid ICmp Predicate");
899 }
900 break;
901 case Instruction::FCmp:
902 Out << "getFCmp(FCmpInst::FCMP_";
903 switch (CE->getPredicate()) {
904 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
905 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
906 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
907 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
908 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
909 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
910 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
911 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
912 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
913 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
914 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
915 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
916 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
917 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
918 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
919 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
920 default: error("Invalid FCmp Predicate");
921 }
922 break;
923 case Instruction::Shl: Out << "getShl("; break;
924 case Instruction::LShr: Out << "getLShr("; break;
925 case Instruction::AShr: Out << "getAShr("; break;
926 case Instruction::Select: Out << "getSelect("; break;
927 case Instruction::ExtractElement: Out << "getExtractElement("; break;
928 case Instruction::InsertElement: Out << "getInsertElement("; break;
929 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
930 default:
931 error("Invalid constant expression");
932 break;
933 }
934 Out << getCppName(CE->getOperand(0));
935 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
936 Out << ", " << getCppName(CE->getOperand(i));
937 Out << ");";
938 }
939 } else {
940 error("Bad Constant");
941 Out << "Constant* " << constName << " = 0; ";
942 }
943 nl(Out);
944 }
945
946 void CppWriter::printConstants(const Module* M) {
947 // Traverse all the global variables looking for constant initializers
948 for (Module::const_global_iterator I = TheModule->global_begin(),
949 E = TheModule->global_end(); I != E; ++I)
950 if (I->hasInitializer())
951 printConstant(I->getInitializer());
952
953 // Traverse the LLVM functions looking for constants
954 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
955 FI != FE; ++FI) {
956 // Add all of the basic blocks and instructions
957 for (Function::const_iterator BB = FI->begin(),
958 E = FI->end(); BB != E; ++BB) {
959 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
960 ++I) {
961 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
962 if (Constant* C = dyn_cast(I->getOperand(i))) {
963 printConstant(C);
964 }
933 Out << getCppName(CE->getOperand(0));
934 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
935 Out << ", " << getCppName(CE->getOperand(i));
936 Out << ");";
937 }
938 } else {
939 error("Bad Constant");
940 Out << "Constant* " << constName << " = 0; ";
941 }
942 nl(Out);
943 }
944
945 void CppWriter::printConstants(const Module* M) {
946 // Traverse all the global variables looking for constant initializers
947 for (Module::const_global_iterator I = TheModule->global_begin(),
948 E = TheModule->global_end(); I != E; ++I)
949 if (I->hasInitializer())
950 printConstant(I->getInitializer());
951
952 // Traverse the LLVM functions looking for constants
953 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
954 FI != FE; ++FI) {
955 // Add all of the basic blocks and instructions
956 for (Function::const_iterator BB = FI->begin(),
957 E = FI->end(); BB != E; ++BB) {
958 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
959 ++I) {
960 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
961 if (Constant* C = dyn_cast(I->getOperand(i))) {
962 printConstant(C);
965963 }
966964 }
967965 }
968966 }
969967 }
970
971 void CppWriter::printVariableUses(const GlobalVariable *GV) {
972 nl(Out) << "// Type Definitions";
973 nl(Out);
974 printType(GV->getType());
975 if (GV->hasInitializer()) {
976 Constant *Init = GV->getInitializer();
977 printType(Init->getType());
978 if (Function *F = dyn_cast(Init)) {
979 nl(Out)<< "/ Function Declarations"; nl(Out);
980 printFunctionHead(F);
981 } else if (GlobalVariable* gv = dyn_cast(Init)) {
982 nl(Out) << "// Global Variable Declarations"; nl(Out);
983 printVariableHead(gv);
984
985 nl(Out) << "// Global Variable Definitions"; nl(Out);
986 printVariableBody(gv);
987 } else {
988 nl(Out) << "// Constant Definitions"; nl(Out);
989 printConstant(Init);
990 }
991 }
992 }
993
994 void CppWriter::printVariableHead(const GlobalVariable *GV) {
995 nl(Out) << "GlobalVariable* " << getCppName(GV);
996 if (is_inline) {
997 Out << " = mod->getGlobalVariable(mod->getContext(), ";
998 printEscapedString(GV->getName());
999 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
1000 nl(Out) << "if (!" << getCppName(GV) << ") {";
1001 in(); nl(Out) << getCppName(GV);
1002 }
1003 Out << " = new GlobalVariable(/*Module=*/*mod, ";
1004 nl(Out) << "/*Type=*/";
1005 printCppName(GV->getType()->getElementType());
1006 Out << ",";
1007 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1008 Out << ",";
1009 nl(Out) << "/*Linkage=*/";
1010 printLinkageType(GV->getLinkage());
1011 Out << ",";
1012 nl(Out) << "/*Initializer=*/0, ";
1013 if (GV->hasInitializer()) {
1014 Out << "// has initializer, specified below";
1015 }
1016 nl(Out) << "/*Name=*/\"";
968 }
969
970 void CppWriter::printVariableUses(const GlobalVariable *GV) {
971 nl(Out) << "// Type Definitions";
972 nl(Out);
973 printType(GV->getType());
974 if (GV->hasInitializer()) {
975 Constant *Init = GV->getInitializer();
976 printType(Init->getType());
977 if (Function *F = dyn_cast(Init)) {
978 nl(Out)<< "/ Function Declarations"; nl(Out);
979 printFunctionHead(F);
980 } else if (GlobalVariable* gv = dyn_cast(Init)) {
981 nl(Out) << "// Global Variable Declarations"; nl(Out);
982 printVariableHead(gv);
983
984 nl(Out) << "// Global Variable Definitions"; nl(Out);
985 printVariableBody(gv);
986 } else {
987 nl(Out) << "// Constant Definitions"; nl(Out);
988 printConstant(Init);
989 }
990 }
991 }
992
993 void CppWriter::printVariableHead(const GlobalVariable *GV) {
994 nl(Out) << "GlobalVariable* " << getCppName(GV);
995 if (is_inline) {
996 Out << " = mod->getGlobalVariable(mod->getContext(), ";
1017997 printEscapedString(GV->getName());
998 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
999 nl(Out) << "if (!" << getCppName(GV) << ") {";
1000 in(); nl(Out) << getCppName(GV);
1001 }
1002 Out << " = new GlobalVariable(/*Module=*/*mod, ";
1003 nl(Out) << "/*Type=*/";
1004 printCppName(GV->getType()->getElementType());
1005 Out << ",";
1006 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1007 Out << ",";
1008 nl(Out) << "/*Linkage=*/";
1009 printLinkageType(GV->getLinkage());
1010 Out << ",";
1011 nl(Out) << "/*Initializer=*/0, ";
1012 if (GV->hasInitializer()) {
1013 Out << "// has initializer, specified below";
1014 }
1015 nl(Out) << "/*Name=*/\"";
1016 printEscapedString(GV->getName());
1017 Out << "\");";
1018 nl(Out);
1019
1020 if (GV->hasSection()) {
1021 printCppName(GV);
1022 Out << "->setSection(\"";
1023 printEscapedString(GV->getSection());
10181024 Out << "\");";
10191025 nl(Out);
1020
1021 if (GV->hasSection()) {
1022 printCppName(GV);
1023 Out << "->setSection(\"";
1024 printEscapedString(GV->getSection());
1025 Out << "\");";
1026 nl(Out);
1027 }
1028 if (GV->getAlignment()) {
1029 printCppName(GV);
1030 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1031 nl(Out);
1032 }
1033 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1034 printCppName(GV);
1035 Out << "->setVisibility(";
1036 printVisibilityType(GV->getVisibility());
1037 Out << ");";
1038 nl(Out);
1039 }
1040 if (GV->isThreadLocal()) {
1041 printCppName(GV);
1042 Out << "->setThreadLocal(true);";
1043 nl(Out);
1044 }
1045 if (is_inline) {
1046 out(); Out << "}"; nl(Out);
1047 }
1048 }
1049
1050 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1051 if (GV->hasInitializer()) {
1052 printCppName(GV);
1053 Out << "->setInitializer(";
1054 Out << getCppName(GV->getInitializer()) << ");";
1055 nl(Out);
1056 }
1057 }
1058
1059 std::string CppWriter::getOpName(Value* V) {
1060 if (!isa(V) || DefinedValues.find(V) != DefinedValues.end())
1061 return getCppName(V);
1062
1063 // See if its alread in the map of forward references, if so just return the
1064 // name we already set up for it
1065 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1066 if (I != ForwardRefs.end())
1067 return I->second;
1068
1069 // This is a new forward reference. Generate a unique name for it
1070 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1071
1072 // Yes, this is a hack. An Argument is the smallest instantiable value that
1073 // we can make as a placeholder for the real value. We'll replace these
1074 // Argument instances later.
1075 Out << "Argument* " << result << " = new Argument("
1076 << getCppName(V->getType()) << ");";
1077 nl(Out);
1078 ForwardRefs[V] = result;
1079 return result;
1080 }
1081
1082 // printInstruction - This member is called for each Instruction in a function.
1083 void CppWriter::printInstruction(const Instruction *I,
1084 const std::string& bbname) {
1085 std::string iName(getCppName(I));
1086
1087 // Before we emit this instruction, we need to take care of generating any
1088 // forward references. So, we get the names of all the operands in advance
1089 const unsigned Ops(I->getNumOperands());
1090 std::string* opNames = new std::string[Ops];
1091 for (unsigned i = 0; i < Ops; i++) {
1092 opNames[i] = getOpName(I->getOperand(i));
1093 }
1094
1026 }
1027 if (GV->getAlignment()) {
1028 printCppName(GV);
1029 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1030 nl(Out);
1031 }
1032 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1033 printCppName(GV);
1034 Out << "->setVisibility(";
1035 printVisibilityType(GV->getVisibility());
1036 Out << ");";
1037 nl(Out);
1038 }
1039 if (GV->isThreadLocal()) {
1040 printCppName(GV);
1041 Out << "->setThreadLocal(true);";
1042 nl(Out);
1043 }
1044 if (is_inline) {
1045 out(); Out << "}"; nl(Out);
1046 }
1047 }
1048
1049 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1050 if (GV->hasInitializer()) {
1051 printCppName(GV);
1052 Out << "->setInitializer(";
1053 Out << getCppName(GV->getInitializer()) << ");";
1054 nl(Out);
1055 }
1056 }
1057
1058 std::string CppWriter::getOpName(Value* V) {
1059 if (!isa(V) || DefinedValues.find(V) != DefinedValues.end())
1060 return getCppName(V);
1061
1062 // See if its alread in the map of forward references, if so just return the
1063 // name we already set up for it
1064 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1065 if (I != ForwardRefs.end())
1066 return I->second;
1067
1068 // This is a new forward reference. Generate a unique name for it
1069 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1070
1071 // Yes, this is a hack. An Argument is the smallest instantiable value that
1072 // we can make as a placeholder for the real value. We'll replace these
1073 // Argument instances later.
1074 Out << "Argument* " << result << " = new Argument("
1075 << getCppName(V->getType()) << ");";
1076 nl(Out);
1077 ForwardRefs[V] = result;
1078 return result;
1079 }
1080
1081 // printInstruction - This member is called for each Instruction in a function.
1082 void CppWriter::printInstruction(const Instruction *I,
1083 const std::string& bbname) {
1084 std::string iName(getCppName(I));
1085
1086 // Before we emit this instruction, we need to take care of generating any
1087 // forward references. So, we get the names of all the operands in advance
1088 const unsigned Ops(I->getNumOperands());
1089 std::string* opNames = new std::string[Ops];
1090 for (unsigned i = 0; i < Ops; i++) {
1091 opNames[i] = getOpName(I->getOperand(i));
1092 }
1093
1094 switch (I->getOpcode()) {
1095 default:
1096 error("Invalid instruction");
1097 break;
1098
1099 case Instruction::Ret: {
1100 const ReturnInst* ret = cast(I);
1101 Out << "ReturnInst::Create(mod->getContext(), "
1102 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1103 break;
1104 }
1105 case Instruction::Br: {
1106 const BranchInst* br = cast(I);
1107 Out << "BranchInst::Create(" ;
1108 if (br->getNumOperands() == 3 ) {
1109 Out << opNames[2] << ", "
1110 << opNames[1] << ", "
1111 << opNames[0] << ", ";
1112
1113 } else if (br->getNumOperands() == 1) {
1114 Out << opNames[0] << ", ";
1115 } else {
1116 error("Branch with 2 operands?");
1117 }
1118 Out << bbname << ");";
1119 break;
1120 }
1121 case Instruction::Switch: {
1122 const SwitchInst *SI = cast(I);
1123 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1124 << opNames[0] << ", "
1125 << opNames[1] << ", "
1126 << SI->getNumCases() << ", " << bbname << ");";
1127 nl(Out);
1128 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
1129 Out << iName << "->addCase("
1130 << opNames[i] << ", "
1131 << opNames[i+1] << ");";
1132 nl(Out);
1133 }
1134 break;
1135 }
1136 case Instruction::IndirectBr: {
1137 const IndirectBrInst *IBI = cast(I);
1138 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1139 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1140 nl(Out);
1141 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1142 Out << iName << "->addDestination(" << opNames[i] << ");";
1143 nl(Out);
1144 }
1145 break;
1146 }
1147 case Instruction::Invoke: {
1148 const InvokeInst* inv = cast(I);
1149 Out << "std::vector " << iName << "_params;";
1150 nl(Out);
1151 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1152 Out << iName << "_params.push_back("
1153 << getOpName(inv->getArgOperand(i)) << ");";
1154 nl(Out);
1155 }
1156 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1157 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1158 << getOpName(inv->getCalledFunction()) << ", "
1159 << getOpName(inv->getNormalDest()) << ", "
1160 << getOpName(inv->getUnwindDest()) << ", "
1161 << iName << "_params.begin(), "
1162 << iName << "_params.end(), \"";
1163 printEscapedString(inv->getName());
1164 Out << "\", " << bbname << ");";
1165 nl(Out) << iName << "->setCallingConv(";
1166 printCallingConv(inv->getCallingConv());
1167 Out << ");";
1168 printAttributes(inv->getAttributes(), iName);
1169 Out << iName << "->setAttributes(" << iName << "_PAL);";
1170 nl(Out);
1171 break;
1172 }
1173 case Instruction::Unwind: {
1174 Out << "new UnwindInst("
1175 << bbname << ");";
1176 break;
1177 }
1178 case Instruction::Unreachable: {
1179 Out << "new UnreachableInst("
1180 << "mod->getContext(), "
1181 << bbname << ");";
1182 break;
1183 }
1184 case Instruction::Add:
1185 case Instruction::FAdd:
1186 case Instruction::Sub:
1187 case Instruction::FSub:
1188 case Instruction::Mul:
1189 case Instruction::FMul:
1190 case Instruction::UDiv:
1191 case Instruction::SDiv:
1192 case Instruction::FDiv:
1193 case Instruction::URem:
1194 case Instruction::SRem:
1195 case Instruction::FRem:
1196 case Instruction::And:
1197 case Instruction::Or:
1198 case Instruction::Xor:
1199 case Instruction::Shl:
1200 case Instruction::LShr:
1201 case Instruction::AShr:{
1202 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
10951203 switch (I->getOpcode()) {
1096 default:
1097 error("Invalid instruction");
1098 break;
1099
1100 case Instruction::Ret: {
1101 const ReturnInst* ret = cast(I);
1102 Out << "ReturnInst::Create(mod->getContext(), "
1103 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1104 break;
1105 }
1106 case Instruction::Br: {
1107 const BranchInst* br = cast(I);
1108 Out << "BranchInst::Create(" ;
1109 if (br->getNumOperands() == 3 ) {
1110 Out << opNames[2] << ", "
1111 << opNames[1] << ", "
1112 << opNames[0] << ", ";
1113
1114 } else if (br->getNumOperands() == 1) {
1115 Out << opNames[0] << ", ";
1116 } else {
1117 error("Branch with 2 operands?");
1118 }
1119 Out << bbname << ");";
1120 break;
1121 }
1122 case Instruction::Switch: {
1123 const SwitchInst *SI = cast(I);
1124 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1125 << opNames[0] << ", "
1126 << opNames[1] << ", "
1127 << SI->getNumCases() << ", " << bbname << ");";
1128 nl(Out);
1129 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
1130 Out << iName << "->addCase("
1131 << opNames[i] << ", "
1132 << opNames[i+1] << ");";
1204 case Instruction::Add: Out << "Instruction::Add"; break;
1205 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1206 case Instruction::Sub: Out << "Instruction::Sub"; break;
1207 case Instruction::FSub: Out << "Instruction::FSub"; break;
1208 case Instruction::Mul: Out << "Instruction::Mul"; break;
1209 case Instruction::FMul: Out << "Instruction::FMul"; break;
1210 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1211 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1212 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1213 case Instruction::URem:Out << "Instruction::URem"; break;
1214 case Instruction::SRem:Out << "Instruction::SRem"; break;
1215 case Instruction::FRem:Out << "Instruction::FRem"; break;
1216 case Instruction::And: Out << "Instruction::And"; break;
1217 case Instruction::Or: Out << "Instruction::Or"; break;
1218 case Instruction::Xor: Out << "Instruction::Xor"; break;
1219 case Instruction::Shl: Out << "Instruction::Shl"; break;
1220 case Instruction::LShr:Out << "Instruction::LShr"; break;
1221 case Instruction::AShr:Out << "Instruction::AShr"; break;
1222 default: Out << "Instruction::BadOpCode"; break;
1223 }
1224 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1225 printEscapedString(I->getName());
1226 Out << "\", " << bbname << ");";
1227 break;
1228 }
1229 case Instruction::FCmp: {
1230 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1231 switch (cast(I)->getPredicate()) {
1232 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1233 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1234 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1235 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1236 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1237 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1238 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1239 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1240 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1241 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1242 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1243 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1244 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1245 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1246 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1247 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1248 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1249 }
1250 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1251 printEscapedString(I->getName());
1252 Out << "\");";
1253 break;
1254 }
1255 case Instruction::ICmp: {
1256 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1257 switch (cast(I)->getPredicate()) {
1258 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1259 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1260 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1261 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1262 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1263 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1264 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1265 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1266 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1267 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1268 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1269 }
1270 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1271 printEscapedString(I->getName());
1272 Out << "\");";
1273 break;
1274 }
1275 case Instruction::Alloca: {
1276 const AllocaInst* allocaI = cast(I);
1277 Out << "AllocaInst* " << iName << " = new AllocaInst("
1278 << getCppName(allocaI->getAllocatedType()) << ", ";
1279 if (allocaI->isArrayAllocation())
1280 Out << opNames[0] << ", ";
1281 Out << "\"";
1282 printEscapedString(allocaI->getName());
1283 Out << "\", " << bbname << ");";
1284 if (allocaI->getAlignment())
1285 nl(Out) << iName << "->setAlignment("
1286 << allocaI->getAlignment() << ");";
1287 break;
1288 }
1289 case Instruction::Load:{
1290 const LoadInst* load = cast(I);
1291 Out << "LoadInst* " << iName << " = new LoadInst("
1292 << opNames[0] << ", \"";
1293 printEscapedString(load->getName());
1294 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1295 << ", " << bbname << ");";
1296 break;
1297 }
1298 case Instruction::Store: {
1299 const StoreInst* store = cast(I);
1300 Out << " new StoreInst("
1301 << opNames[0] << ", "
1302 << opNames[1] << ", "
1303 << (store->isVolatile() ? "true" : "false")
1304 << ", " << bbname << ");";
1305 break;
1306 }
1307 case Instruction::GetElementPtr: {
1308 const GetElementPtrInst* gep = cast(I);
1309 if (gep->getNumOperands() <= 2) {
1310 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1311 << opNames[0];
1312 if (gep->getNumOperands() == 2)
1313 Out << ", " << opNames[1];
1314 } else {
1315 Out << "std::vector " << iName << "_indices;";
1316 nl(Out);
1317 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1318 Out << iName << "_indices.push_back("
1319 << opNames[i] << ");";
11331320 nl(Out);
11341321 }
1135 break;
1136 }
1137 case Instruction::IndirectBr: {
1138 const IndirectBrInst *IBI = cast(I);
1139 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1140 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1141 nl(Out);
1142 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1143 Out << iName << "->addDestination(" << opNames[i] << ");";
1322 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1323 << opNames[0] << ", " << iName << "_indices.begin(), "
1324 << iName << "_indices.end()";
1325 }
1326 Out << ", \"";
1327 printEscapedString(gep->getName());
1328 Out << "\", " << bbname << ");";
1329 break;
1330 }
1331 case Instruction::PHI: {
1332 const PHINode* phi = cast(I);
1333
1334 Out << "PHINode* " << iName << " = PHINode::Create("
1335 << getCppName(phi->getType()) << ", \"";
1336 printEscapedString(phi->getName());
1337 Out << "\", " << bbname << ");";
1338 nl(Out) << iName << "->reserveOperandSpace("
1339 << phi->getNumIncomingValues()
1340 << ");";
1341 nl(Out);
1342 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1343 Out << iName << "->addIncoming("
1344 << opNames[i] << ", " << opNames[i+1] << ");";
1345 nl(Out);
1346 }
1347 break;
1348 }
1349 case Instruction::Trunc:
1350 case Instruction::ZExt:
1351 case Instruction::SExt:
1352 case Instruction::FPTrunc:
1353 case Instruction::FPExt:
1354 case Instruction::FPToUI:
1355 case Instruction::FPToSI:
1356 case Instruction::UIToFP:
1357 case Instruction::SIToFP:
1358 case Instruction::PtrToInt:
1359 case Instruction::IntToPtr:
1360 case Instruction::BitCast: {
1361 const CastInst* cst = cast(I);
1362 Out << "CastInst* " << iName << " = new ";
1363 switch (I->getOpcode()) {
1364 case Instruction::Trunc: Out << "TruncInst"; break;
1365 case Instruction::ZExt: Out << "ZExtInst"; break;
1366 case Instruction::SExt: Out << "SExtInst"; break;
1367 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1368 case Instruction::FPExt: Out << "FPExtInst"; break;
1369 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1370 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1371 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1372 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1373 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1374 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1375 case Instruction::BitCast: Out << "BitCastInst"; break;
1376 default: assert(!"Unreachable"); break;
1377 }
1378 Out << "(" << opNames[0] << ", "
1379 << getCppName(cst->getType()) << ", \"";
1380 printEscapedString(cst->getName());
1381 Out << "\", " << bbname << ");";
1382 break;
1383 }
1384 case Instruction::Call:{
1385 const CallInst* call = cast(I);
1386 if (const InlineAsm* ila = dyn_cast(call->getCalledValue())) {
1387 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1388 << getCppName(ila->getFunctionType()) << ", \""
1389 << ila->getAsmString() << "\", \""
1390 << ila->getConstraintString() << "\","
1391 << (ila->hasSideEffects() ? "true" : "false") << ");";
1392 nl(Out);
1393 }
1394 if (call->getNumOperands() > 2) {
1395 Out << "std::vector " << iName << "_params;";
1396 nl(Out);
1397 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1398 Out << iName << "_params.push_back(" << opNames[i] << ");";
11441399 nl(Out);
11451400 }
1146 break;
1147 }
1148 case Instruction::Invoke: {
1149 const InvokeInst* inv = cast(I);
1150 Out << "std::vector " << iName << "_params;";
1151 nl(Out);
1152 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1153 Out << iName << "_params.push_back("
1154 << getOpName(inv->getArgOperand(i)) << ");";
1155 nl(Out);
1156 }
1157 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1158 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1159 << getOpName(inv->getCalledFunction()) << ", "
1160 << getOpName(inv->getNormalDest()) << ", "
1161 << getOpName(inv->getUnwindDest()) << ", "
1162 << iName << "_params.begin(), "
1401 Out << "CallInst* " << iName << " = CallInst::Create("
1402 << opNames[0] << ", " << iName << "_params.begin(), "
11631403 << iName << "_params.end(), \"";
1164 printEscapedString(inv->getName());
1165 Out << "\", " << bbname << ");";
1166 nl(Out) << iName << "->setCallingConv(";
1167 printCallingConv(inv->getCallingConv());
1168 Out << ");";
1169 printAttributes(inv->getAttributes(), iName);
1170 Out << iName << "->setAttributes(" << iName << "_PAL);";
1171 nl(Out);
1172 break;
1173 }
1174 case Instruction::Unwind: {
1175 Out << "new UnwindInst("
1176 << bbname << ");";
1177 break;
1178 }
1179 case Instruction::Unreachable: {
1180 Out << "new UnreachableInst("
1181 << "mod->getContext(), "
1182 << bbname << ");";
1183 break;
1184 }
1185 case Instruction::Add:
1186 case Instruction::FAdd:
1187 case Instruction::Sub:
1188 case Instruction::FSub:
1189 case Instruction::Mul:
1190 case Instruction::FMul:
1191 case Instruction::UDiv:
1192 case Instruction::SDiv:
1193 case Instruction::FDiv:
1194 case Instruction::URem:
1195 case Instruction::SRem:
1196 case Instruction::FRem:
1197 case Instruction::And:
1198 case Instruction::Or:
1199 case Instruction::Xor:
1200 case Instruction::Shl:
1201 case Instruction::LShr:
1202 case Instruction::AShr:{
1203 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1204 switch (I->getOpcode()) {
1205 case Instruction::Add: Out << "Instruction::Add"; break;
1206 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1207 case Instruction::Sub: Out << "Instruction::Sub"; break;
1208 case Instruction::FSub: Out << "Instruction::FSub"; break;
1209 case Instruction::Mul: Out << "Instruction::Mul"; break;
1210 case Instruction::FMul: Out << "Instruction::FMul"; break;
1211 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1212 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1213 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1214 case Instruction::URem:Out << "Instruction::URem"; break;
1215 case Instruction::SRem:Out << "Instruction::SRem"; break;
1216 case Instruction::FRem:Out << "Instruction::FRem"; break;
1217 case Instruction::And: Out << "Instruction::And"; break;
1218 case Instruction::Or: Out << "Instruction::Or"; break;
1219 case Instruction::Xor: Out << "Instruction::Xor"; break;
1220 case Instruction::Shl: Out << "Instruction::Shl"; break;
1221 case Instruction::LShr:Out << "Instruction::LShr"; break;
1222 case Instruction::AShr:Out << "Instruction::AShr"; break;
1223 default: Out << "Instruction::BadOpCode"; break;
1224 }
1225 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1226 printEscapedString(I->getName());
1227 Out << "\", " << bbname << ");";
1228 break;
1229 }
1230 case Instruction::FCmp: {
1231 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1232 switch (cast(I)->getPredicate()) {
1233 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1234 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1235 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1236 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1237 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1238 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1239 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1240 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1241 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1242 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1243 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1244 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1245 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1246 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1247 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1248 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1249 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1250 }
1251 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1252 printEscapedString(I->getName());
1253 Out << "\");";
1254 break;
1255 }
1256 case Instruction::ICmp: {
1257 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1258 switch (cast(I)->getPredicate()) {
1259 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1260 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1261 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1262 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1263 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1264 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1265 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1266 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1267 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1268 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1269 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1270 }
1271 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1272 printEscapedString(I->getName());
1273 Out << "\");";
1274 break;
1275 }
1276 case Instruction::Alloca: {
1277 const AllocaInst* allocaI = cast(I);
1278 Out << "AllocaInst* " << iName << " = new AllocaInst("
1279 << getCppName(allocaI->getAllocatedType()) << ", ";
1280 if (allocaI->isArrayAllocation())
1281 Out << opNames[0] << ", ";
1282 Out << "\"";
1283 printEscapedString(allocaI->getName());
1284 Out << "\", " << bbname << ");";
1285 if (allocaI->getAlignment())
1286 nl(Out) << iName << "->setAlignment("
1287 << allocaI->getAlignment() << ");";
1288 break;
1289 }
1290 case Instruction::Load:{
1291 const LoadInst* load = cast(I);
1292 Out << "LoadInst* " << iName << " = new LoadInst("
1293 << opNames[0] << ", \"";
1294 printEscapedString(load->getName());
1295 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1296 << ", " << bbname << ");";
1297 break;
1298 }
1299 case Instruction::Store: {
1300 const StoreInst* store = cast(I);
1301 Out << " new StoreInst("
1302 << opNames[0] << ", "
1303 << opNames[1] << ", "
1304 << (store->isVolatile() ? "true" : "false")
1305 << ", " << bbname << ");";
1306 break;
1307 }
1308 case Instruction::GetElementPtr: {
1309 const GetElementPtrInst* gep = cast(I);
1310 if (gep->getNumOperands() <= 2) {
1311 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1312 << opNames[0];
1313 if (gep->getNumOperands() == 2)
1314 Out << ", " << opNames[1];
1315 } else {
1316 Out << "std::vector " << iName << "_indices;";
1317 nl(Out);
1318 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1319 Out << iName << "_indices.push_back("
1320 << opNames[i] << ");";
1321 nl(Out);
1322 }
1323 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1324 << opNames[0] << ", " << iName << "_indices.begin(), "
1325 << iName << "_indices.end()";
1326 }
1327 Out << ", \"";
1328 printEscapedString(gep->getName());
1329 Out << "\", " << bbname << ");";
1330 break;
1331 }
1332 case Instruction::PHI: {
1333 const PHINode* phi = cast(I);
1334
1335 Out << "PHINode* " << iName << " = PHINode::Create("
1336 << getCppName(phi->getType()) << ", \"";
1337 printEscapedString(phi->getName());
1338 Out << "\", " << bbname << ");";
1339 nl(Out) << iName << "->reserveOperandSpace("
1340 << phi->getNumIncomingValues()
1341 << ");";
1342 nl(Out);
1343 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1344 Out << iName << "->addIncoming("
1345 << opNames[i] << ", " << opNames[i+1] << ");";
1346 nl(Out);
1347 }
1348 break;
1349 }
1350 case Instruction::Trunc:
1351 case Instruction::ZExt:
1352 case Instruction::SExt:
1353 case Instruction::FPTrunc:
1354 case Instruction::FPExt:
1355 case Instruction::FPToUI:
1356 case Instruction::FPToSI:
1357 case Instruction::UIToFP:
1358 case Instruction::SIToFP:
1359 case Instruction::PtrToInt:
1360 case Instruction::IntToPtr:
1361 case Instruction::BitCast: {
1362 const CastInst* cst = cast(I);
1363 Out << "CastInst* " << iName << " = new ";
1364 switch (I->getOpcode()) {
1365 case Instruction::Trunc: Out << "TruncInst"; break;
1366 case Instruction::ZExt: Out << "ZExtInst"; break;
1367 case Instruction::SExt: Out << "SExtInst"; break;
1368 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1369 case Instruction::FPExt: Out << "FPExtInst"; break;
1370 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1371 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1372 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1373 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1374 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1375 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1376 case Instruction::BitCast: Out << "BitCastInst"; break;
1377 default: assert(!"Unreachable"); break;
1378 }
1379 Out << "(" << opNames[0] << ", "
1380 << getCppName(cst->getType()) << ", \"";
1381 printEscapedString(cst->getName());
1382 Out << "\", " << bbname << ");";
1383 break;
1384 }
1385 case Instruction::Call:{
1386 const CallInst* call = cast(I);
1387 if (const InlineAsm* ila = dyn_cast(call->getCalledValue())) {
1388 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1389 << getCppName(ila->getFunctionType()) << ", \""
1390 << ila->getAsmString() << "\", \""
1391 << ila->getConstraintString() << "\","
1392 << (ila->hasSideEffects() ? "true" : "false") << ");";
1393 nl(Out);
1394 }
1395 if (call->getNumOperands() > 2) {
1396 Out << "std::vector " << iName << "_params;";
1397 nl(Out);
1398 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1399 Out << iName << "_params.push_back(" << opNames[i] << ");";
1400 nl(Out);
1401 }
1402 Out << "CallInst* " << iName << " = CallInst::Create("
1403 << opNames[0] << ", " << iName << "_params.begin(), "
1404 << iName << "_params.end(), \"";
1405 } else if (call->getNumOperands() == 2) {
1406 Out << "CallInst* " << iName << " = CallInst::Create("
1407 << opNames[0] << ", " << opNames[1] << ", \"";
1408 } else {
1409 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1410 << ", \"";
1411 }
1412 printEscapedString(call->getName());
1413 Out << "\", " << bbname << ");";
1414 nl(Out) << iName << "->setCallingConv(";
1415 printCallingConv(call->getCallingConv());
1416 Out << ");";
1417 nl(Out) << iName << "->setTailCall("
1418 << (call->isTailCall() ? "true":"false");
1419 Out << ");";
1420 printAttributes(call->getAttributes(), iName);
1421 Out << iName << "->setAttributes(" << iName << "_PAL);";
1422 nl(Out);
1423 break;
1424 }
1425 case Instruction::Select: {
1426 const SelectInst* sel = cast(I);
1427 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1428 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1429 printEscapedString(sel->getName());
1430 Out << "\", " << bbname << ");";
1431 break;
1432 }
1433 case Instruction::UserOp1:
1434 /// FALL THROUGH
1435 case Instruction::UserOp2: {
1436 /// FIXME: What should be done here?
1437 break;
1438 }
1439 case Instruction::VAArg: {
1440 const VAArgInst* va = cast(I);
1441 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1442 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1443 printEscapedString(va->getName());
1444 Out << "\", " << bbname << ");";
1445 break;
1446 }
1447 case Instruction::ExtractElement: {
1448 const ExtractElementInst* eei = cast(I);
1449 Out << "ExtractElementInst* " << getCppName(eei)
1450 << " = new ExtractElementInst(" << opNames[0]
1451 << ", " << opNames[1] << ", \"";
1452 printEscapedString(eei->getName());
1453 Out << "\", " << bbname << ");";
1454 break;
1455 }
1456 case Instruction::InsertElement: {
1457 const InsertElementInst* iei = cast(I);
1458 Out << "InsertElementInst* " << getCppName(iei)
1459 << " = InsertElementInst::Create(" << opNames[0]
1460 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1461 printEscapedString(iei->getName());
1462 Out << "\", " << bbname << ");";
1463 break;
1464 }
1465 case Instruction::ShuffleVector: {
1466 const ShuffleVectorInst* svi = cast(I);
1467 Out << "ShuffleVectorInst* " << getCppName(svi)
1468 << " = new ShuffleVectorInst(" << opNames[0]
1469 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1470 printEscapedString(svi->getName());
1471 Out << "\", " << bbname << ");";
1472 break;
1473 }
1474 case Instruction::ExtractValue: {
1475 const ExtractValueInst *evi = cast(I);
1476 Out << "std::vector " << iName << "_indices;";
1477 nl(Out);
1478 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1479 Out << iName << "_indices.push_back("
1480 << evi->idx_begin()[i] << ");";
1481 nl(Out);
1482 }
1483 Out << "ExtractValueInst* " << getCppName(evi)
1484 << " = ExtractValueInst::Create(" << opNames[0]
1485 << ", "
1486 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1487 printEscapedString(evi->getName());
1488 Out << "\", " << bbname << ");";
1489 break;
1490 }
1491 case Instruction::InsertValue: {
1492 const InsertValueInst *ivi = cast(I);
1493 Out << "std::vector " << iName << "_indices;";
1494 nl(Out);
1495 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1496 Out << iName << "_indices.push_back("
1497 << ivi->idx_begin()[i] << ");";
1498 nl(Out);
1499 }
1500 Out << "InsertValueInst* " << getCppName(ivi)
1501 << " = InsertValueInst::Create(" << opNames[0]
1502 << ", " << opNames[1] << ", "
1503 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1504 printEscapedString(ivi->getName());
1505 Out << "\", " << bbname << ");";
1506 break;
1507 }
1404 } else if (call->getNumOperands() == 2) {
1405 Out << "CallInst* " << iName << " = CallInst::Create("
1406 << opNames[0] << ", " << opNames[1] << ", \"";
1407 } else {
1408 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1409 << ", \"";
1410 }
1411 printEscapedString(call->getName());
1412 Out << "\", " << bbname << ");";
1413 nl(Out) << iName << "->setCallingConv(";
1414 printCallingConv(call->getCallingConv());
1415 Out << ");";
1416 nl(Out) << iName << "->setTailCall("
1417 << (call->isTailCall() ? "true":"false");
1418 Out << ");";
1419 printAttributes(call->getAttributes(), iName);
1420 Out << iName << "->setAttributes(" << iName << "_PAL);";
1421 nl(Out);
1422 break;
1423 }
1424 case Instruction::Select: {
1425 const SelectInst* sel = cast(I);
1426 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1427 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1428 printEscapedString(sel->getName());
1429 Out << "\", " << bbname << ");";
1430 break;
1431 }
1432 case Instruction::UserOp1:
1433 /// FALL THROUGH
1434 case Instruction::UserOp2: {
1435 /// FIXME: What should be done here?
1436 break;
1437 }
1438 case Instruction::VAArg: {
1439 const VAArgInst* va = cast(I);
1440 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1441 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1442 printEscapedString(va->getName());
1443 Out << "\", " << bbname << ");";
1444 break;
1445 }
1446 case Instruction::ExtractElement: {
1447 const ExtractElementInst* eei = cast(I);
1448 Out << "ExtractElementInst* " << getCppName(eei)
1449 << " = new ExtractElementInst(" << opNames[0]
1450 << ", " << opNames[1] << ", \"";
1451 printEscapedString(eei->getName());
1452 Out << "\", " << bbname << ");";
1453 break;
1454 }
1455 case Instruction::InsertElement: {
1456 const InsertElementInst* iei = cast(I);
1457 Out << "InsertElementInst* " << getCppName(iei)
1458 << " = InsertElementInst::Create(" << opNames[0]
1459 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1460 printEscapedString(iei->getName());
1461 Out << "\", " << bbname << ");";
1462 break;
1463 }
1464 case Instruction::ShuffleVector: {
1465 const ShuffleVectorInst* svi = cast(I);
1466 Out << "ShuffleVectorInst* " << getCppName(svi)
1467 << " = new ShuffleVectorInst(" << opNames[0]
1468 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1469 printEscapedString(svi->getName());
1470 Out << "\", " << bbname << ");";
1471 break;
1472 }
1473 case Instruction::ExtractValue: {
1474 const ExtractValueInst *evi = cast(I);
1475 Out << "std::vector " << iName << "_indices;";
1476 nl(Out);
1477 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1478 Out << iName << "_indices.push_back("
1479 << evi->idx_begin()[i] << ");";
1480 nl(Out);
1481 }
1482 Out << "ExtractValueInst* " << getCppName(evi)
1483 << " = ExtractValueInst::Create(" << opNames[0]
1484 << ", "
1485 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1486 printEscapedString(evi->getName());
1487 Out << "\", " << bbname << ");";
1488 break;
1489 }
1490 case Instruction::InsertValue: {
1491 const InsertValueInst *ivi = cast(I);
1492 Out << "std::vector " << iName << "_indices;";
1493 nl(Out);
1494 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1495 Out << iName << "_indices.push_back("
1496 << ivi->idx_begin()[i] << ");";
1497 nl(Out);
1498 }
1499 Out << "InsertValueInst* " << getCppName(ivi)
1500 << " = InsertValueInst::Create(" << opNames[0]
1501 << ", " << opNames[1] << ", "
1502 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1503 printEscapedString(ivi->getName());
1504 Out << "\", " << bbname << ");";
1505 break;
1506 }
15081507 }
15091508 DefinedValues.insert(I);
15101509 nl(Out);
15111510 delete [] opNames;
15121511 }
15131512
1514 // Print out the types, constants and declarations needed by one function
1515 void CppWriter::printFunctionUses(const Function* F) {
1516 nl(Out) << "// Type Definitions"; nl(Out);
1517 if (!is_inline) {
1518 // Print the function's return type
1519 printType(F->getReturnType());
1520
1521 // Print the function's function type
1522 printType(F->getFunctionType());
1523
1524 // Print the types of each of the function's arguments
1525 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1526 AI != AE; ++AI) {
1527 printType(AI->getType());
1513 // Print out the types, constants and declarations needed by one function
1514 void CppWriter::printFunctionUses(const Function* F) {
1515 nl(Out) << "// Type Definitions"; nl(Out);
1516 if (!is_inline) {
1517 // Print the function's return type
1518 printType(F->getReturnType());
1519
1520 // Print the function's function type
1521 printType(F->getFunctionType());
1522
1523 // Print the types of each of the function's arguments
1524 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1525 AI != AE; ++AI) {
1526 printType(AI->getType());
1527 }
1528 }
1529
1530 // Print type definitions for every type referenced by an instruction and
1531 // make a note of any global values or constants that are referenced
1532 SmallPtrSet gvs;
1533 SmallPtrSet consts;
1534 for (Function::const_iterator BB = F->begin(), BE = F->end();
1535 BB != BE; ++BB){
1536 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1537 I != E; ++I) {
1538 // Print the type of the instruction itself
1539 printType(I->getType());
1540
1541 // Print the type of each of the instruction's operands
1542 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1543 Value* operand = I->getOperand(i);
1544 printType(operand->getType());
1545
1546 // If the operand references a GVal or Constant, make a note of it
1547 if (GlobalValue* GV = dyn_cast(operand)) {
1548 gvs.insert(GV);
1549 if (GlobalVariable *GVar = dyn_cast(GV))
1550 if (GVar->hasInitializer())
1551 consts.insert(GVar->getInitializer());
1552 } else if (Constant* C = dyn_cast(operand))
1553 consts.insert(C);
15281554 }
15291555 }
1530
1531 // Print type definitions for every type referenced by an instruction and
1532 // make a note of any global values or constants that are referenced
1533 SmallPtrSet gvs;
1534 SmallPtrSet consts;
1535 for (Function::const_iterator BB = F->begin(), BE = F->end();
1536 BB != BE; ++BB){
1537 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1538 I != E; ++I) {
1539 // Print the type of the instruction itself
1540 printType(I->getType());
1541
1542 // Print the type of each of the instruction's operands
1543 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1544 Value* operand = I->getOperand(i);
1545 printType(operand->getType());
1546
1547 // If the operand references a GVal or Constant, make a note of it
1548 if (GlobalValue* GV = dyn_cast(operand)) {
1549 gvs.insert(GV);
1550 if (GlobalVariable *GVar = dyn_cast(GV))
1551 if (GVar->hasInitializer())
1552 consts.insert(GVar->getInitializer());
1553 } else if (Constant* C = dyn_cast(operand))
1554 consts.insert(C);
1555 }
1556 }
1557 }
1558
1559 // Print the function declarations for any functions encountered
1560 nl(Out) << "// Function Declarations"; nl(Out);
1561 for (SmallPtrSet::iterator I = gvs.begin(), E = gvs.end();
1562 I != E; ++I) {
1563 if (Function* Fun = dyn_cast(*I)) {
1564 if (!is_inline || Fun != F)
1565 printFunctionHead(Fun);
1566 }
1567 }
1568
1569 // Print the global variable declarations for any variables encountered
1570 nl(Out) << "// Global Variable Declarations"; nl(Out);
1571 for (SmallPtrSet::iterator I = gvs.begin(), E = gvs.end();
1572 I != E; ++I) {
1573 if (GlobalVariable* F = dyn_cast(*I))
1574 printVariableHead(F);
1575 }
1576
1577 // Print the constants found
1578 nl(Out) << "// Constant Definitions"; nl(Out);
1579 for (SmallPtrSet::iterator I = consts.begin(),
1580 E = consts.end(); I != E; ++I) {
1581 printConstant(*I);
1582 }
1583
1584 // Process the global variables definitions now that all the constants have
1585 // been emitted. These definitions just couple the gvars with their constant
1586 // initializers.
1587 nl(Out) << "// Global Variable Definitions"; nl(Out);
1588 for (SmallPtrSet::iterator I = gvs.begin(), E = gvs.end();
1589 I != E; ++I) {
1590 if (GlobalVariable* GV = dyn_cast(*I))
1591 printVariableBody(GV);
1592 }
1593 }
1594
1595 void CppWriter::printFunctionHead(const Function* F) {
1596 nl(Out) << "Function* " << getCppName(F);
1597 if (is_inline) {
1598 Out << " = mod->getFunction(\"";
1599 printEscapedString(F->getName());
1600 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1601 nl(Out) << "if (!" << getCppName(F) << ") {";
1602 nl(Out) << getCppName(F);
1603 }
1604 Out<< " = Function::Create(";
1605 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1606 nl(Out) << "/*Linkage=*/";
1607 printLinkageType(F->getLinkage());
1608 Out << ",";
1609 nl(Out) << "/*Name=*/\"";
1556 }
1557
1558 // Print the function declarations for any functions encountered
1559 nl(Out) << "// Function Declarations"; nl(Out);
1560 for (SmallPtrSet::iterator I = gvs.begin(), E = gvs.end();
1561 I != E; ++I) {
1562 if (Function* Fun = dyn_cast(*I)) {
1563 if (!is_inline || Fun != F)
1564 printFunctionHead(Fun);
1565 }
1566 }
1567
1568 // Print the global variable declarations for any variables encountered
1569 nl(Out) << "// Global Variable Declarations"; nl(Out);
1570 for (SmallPtrSet::iterator I = gvs.begin(), E = gvs.end();
1571 I != E; ++I) {
1572 if (GlobalVariable* F = dyn_cast(*I))
1573 printVariableHead(F);
1574 }
1575
1576 // Print the constants found
1577 nl(Out) << "// Constant Definitions"; nl(Out);
1578 for (SmallPtrSet::iterator I = consts.begin(),
1579 E = consts.end(); I != E; ++I) {
1580 printConstant(*I);
1581 }
1582
1583 // Process the global variables definitions now that all the constants have
1584 // been emitted. These definitions just couple the gvars with their constant
1585 // initializers.
1586 nl(Out) << "// Global Variable Definitions"; nl(Out);
1587 for (SmallPtrSet::iterator I = gvs.begin(), E = gvs.end();
1588 I != E; ++I) {
1589 if (GlobalVariable* GV = dyn_cast(*I))
1590 printVariableBody(GV);
1591 }
1592 }
1593
1594 void CppWriter::printFunctionHead(const Function* F) {
1595 nl(Out) << "Function* " << getCppName(F);
1596 if (is_inline) {
1597 Out << " = mod->getFunction(\"";
16101598 printEscapedString(F->getName());
1611 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1612 nl(Out,-1);
1599 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1600 nl(Out) << "if (!" << getCppName(F) << ") {";
1601 nl(Out) << getCppName(F);
1602 }
1603 Out<< " = Function::Create(";
1604 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1605 nl(Out) << "/*Linkage=*/";
1606 printLinkageType(F->getLinkage());
1607 Out << ",";
1608 nl(Out) << "/*Name=*/\"";
1609 printEscapedString(F->getName());
1610 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1611 nl(Out,-1);
1612 printCppName(F);
1613 Out << "->setCallingConv(";
1614 printCallingConv(F->getCallingConv());
1615 Out << ");";
1616 nl(Out);
1617 if (F->hasSection()) {
16131618 printCppName(F);
1614 Out << "->setCallingConv(";
1615 printCallingConv(F->getCallingConv());
1619 Out << "->setSection(\"" << F->getSection() << "\");";
1620 nl(Out);
1621 }
1622 if (F->getAlignment()) {
1623 printCppName(F);
1624 Out << "->setAlignment(" << F->getAlignment() << ");";
1625 nl(Out);
1626 }
1627 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1628 printCppName(F);
1629 Out << "->setVisibility(";
1630 printVisibilityType(F->getVisibility());
16161631 Out << ");";
16171632 nl(Out);
1618 if (F->hasSection()) {
1619 printCppName(F);
1620 Out << "->setSection(\"" << F->getSection() << "\");";
1621 nl(Out);
1622 }
1623 if (F->getAlignment()) {
1624 printCppName(F);
1625 Out << "->setAlignment(" << F->getAlignment() << ");";
1626 nl(Out);
1627 }
1628 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1629 printCppName(F);
1630 Out << "->setVisibility(";
1631 printVisibilityType(F->getVisibility());
1632 Out << ");";
1633 nl(Out);
1634 }
1635 if (F->hasGC()) {
1636 printCppName(F);
1637 Out << "->setGC(\"" << F->getGC() << "\");";
1638 nl(Out);
1639 }
1640 if (is_inline) {
1641 Out << "}";
1642 nl(Out);
1643 }
1644 printAttributes(F->getAttributes(), getCppName(F));
1633 }
1634 if (F->hasGC()) {
16451635 printCppName(F);
1646 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1647 nl(Out);
1648 }
1649
1650 void CppWriter::printFunctionBody(const Function *F) {
1651 if (F->isDeclaration())
1652 return; // external functions have no bodies.
1653
1654 // Clear the DefinedValues and ForwardRefs maps because we can't have
1655 // cross-function forward refs
1656 ForwardRefs.clear();
1657 DefinedValues.clear();
1658
1659 // Create all the argument values
1660 if (!is_inline) {
1661 if (!F->arg_empty()) {
1662 Out << "Function::arg_iterator args = " << getCppName(F)
1663 << "->arg_begin();";
1636 Out << "->setGC(\"" << F->getGC() << "\");";
1637 nl(Out);
1638 }
1639 if (is_inline) {
1640 Out << "}";
1641 nl(Out);
1642 }
1643 printAttributes(F->getAttributes(), getCppName(F));
1644 printCppName(F);
1645 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1646 nl(Out);
1647 }
1648
1649 void CppWriter::printFunctionBody(const Function *F) {
1650 if (F->isDeclaration())
1651 return; // external functions have no bodies.
1652
1653 // Clear the DefinedValues and ForwardRefs maps because we can't have
1654 // cross-function forward refs
1655 ForwardRefs.clear();
1656 DefinedValues.clear();
1657
1658 // Create all the argument values
1659 if (!is_inline) {
1660 if (!F->arg_empty()) {
1661 Out << "Function::arg_iterator args = " << getCppName(F)
1662 << "->arg_begin();";
1663 nl(Out);
1664 }
1665 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1666 AI != AE; ++AI) {
1667 Out << "Value* " << getCppName(AI) << " = args++;";
1668 nl(Out);
1669 if (AI->hasName()) {
1670 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
16641671 nl(Out);
16651672 }
1666 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1667 AI != AE; ++AI) {
1668 Out << "Value* " << getCppName(AI) << " = args++;";
1669 nl(Out);
1670 if (AI->hasName()) {
1671 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1672 nl(Out);
1673 }
1674 }
1675 }
1676
1677 // Create all the basic blocks
1678 nl(Out);
1679 for (Function::const_iterator BI = F->begin(), BE = F->end();
1680 BI != BE; ++BI) {
1681 std::string bbname(getCppName(BI));
1682 Out << "BasicBlock* " << bbname <<
1683 " = BasicBlock::Create(mod->getContext(), \"";
1684 if (BI->hasName())
1685 printEscapedString(BI->getName());
1686 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1687 nl(Out);
1688 }
1689
1690 // Output all of its basic blocks... for the function
1691 for (Function::const_iterator BI = F->begin(), BE = F->end();
1692 BI != BE; ++BI) {
1693 std::string bbname(getCppName(BI));
1694 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1695 nl(Out);
1696
1697 // Output all of the instructions in the basic block...
1698 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1699 I != E; ++I) {
1700 printInstruction(I,bbname);
1701 }
1702 }
1703
1704 // Loop over the ForwardRefs and resolve them now that all instructions
1705 // are generated.
1706 if (!ForwardRefs.empty()) {
1707 nl(Out) << "// Resolve Forward References";
1708 nl(Out);
1709 }
1710
1711 while (!ForwardRefs.empty()) {
1712 ForwardRefMap::iterator I = ForwardRefs.begin();
1713 Out << I->second << "->replaceAllUsesWith("
1714 << getCppName(I->first) << "); delete " << I->second << ";";
1715 nl(Out);
1716 ForwardRefs.erase(I);
1717 }
1718 }
1719
1720 void CppWriter::printInline(const std::string& fname,
1721 const std::string& func) {
1722 const Function* F = TheModule->getFunction(func);
1723 if (!F) {
1724 error(std::string("Function '") + func + "' not found in input module");
1725 return;
1726 }
1727 if (F->isDeclaration()) {
1728 error(std::string("Function '") + func + "' is external!");
1729 return;
1730 }
1731 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1732 << getCppName(F);
1733 unsigned arg_count = 1;
1734 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1735 AI != AE; ++AI) {
1736 Out << ", Value* arg_" << arg_count;
1737 }
1738 Out << ") {";
1739 nl(Out);
1740 is_inline = true;
1741 printFunctionUses(F);
1742 printFunctionBody(F);
1743 is_inline = false;
1744 Out << "return " << getCppName(F->begin()) << ";";
1745 nl(Out) << "}";
1746 nl(Out);
1747 }
1748
1749 void CppWriter::printModuleBody() {
1750 // Print out all the type definitions
1751 nl(Out) << "// Type Definitions"; nl(Out);
1752 printTypes(TheModule);
1753
1754 // Functions can call each other and global variables can reference them so
1755 // define all the functions first before emitting their function bodies.
1756 nl(Out) << "// Function Declarations"; nl(Out);
1757 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1758 I != E; ++I)
1759 printFunctionHead(I);
1760
1761 // Process the global variables declarations. We can't initialze them until
1762 // after the constants are printed so just print a header for each global
1763 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1764 for (Module::const_global_iterator I = TheModule->global_begin(),
1765 E = TheModule->global_end(); I != E; ++I) {
1766 printVariableHead(I);
1767 }
1768
1769 // Print out all the constants definitions. Constants don't recurse except
1770 // through GlobalValues. All GlobalValues have been declared at this point
1771 // so we can proceed to generate the constants.
1772 nl(Out) << "// Constant Definitions"; nl(Out);
1773 printConstants(TheModule);
1774
1775 // Process the global variables definitions now that all the constants have
1776 // been emitted. These definitions just couple the gvars with their constant
1777 // initializers.
1778 nl(Out) << "// Global Variable Definitions"; nl(Out);
1779 for (Module::const_global_iterator I = TheModule->global_begin(),
1780 E = TheModule->global_end(); I != E; ++I) {
1781 printVariableBody(I);
1782 }
1783
1784 // Finally, we can safely put out all of the function bodies.
1785 nl(Out) << "// Function Definitions"; nl(Out);
1786 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1673 }
1674 }
1675
1676 // Create all the basic blocks
1677 nl(Out);
1678 for (Function::const_iterator BI = F->begin(), BE = F->end();
1679 BI != BE; ++BI) {
1680 std::string bbname(getCppName(BI));
1681 Out << "BasicBlock* " << bbname <<
1682 " = BasicBlock::Create(mod->getContext(), \"";
1683 if (BI->hasName())
1684 printEscapedString(BI->getName());
1685 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1686 nl(Out);
1687 }
1688
1689 // Output all of its basic blocks... for the function
1690 for (Function::const_iterator BI = F->begin(), BE = F->end();
1691 BI != BE; ++BI) {
1692 std::string bbname(getCppName(BI));
1693 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1694 nl(Out);
1695
1696 // Output all of the instructions in the basic block...
1697 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
17871698 I != E; ++I) {
1788 if (!I->isDeclaration()) {
1789 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1790 << ")";
1791 nl(Out) << "{";
1792 nl(Out,1);
1793 printFunctionBody(I);
1794 nl(Out,-1) << "}";
1795 nl(Out);
1796 }
1797 }
1798 }
1799
1800 void CppWriter::printProgram(const std::string& fname,
1801 const std::string& mName) {
1802 Out << "#include \n";
1803 Out << "#include \n";
1804 Out << "#include \n";
1805 Out << "#include \n";
1806 Out << "#include \n";
1807 Out << "#include \n";
1808 Out << "#include \n";
1809 Out << "#include \n";
1810 Out << "#include \n";
1811 Out << "#include \n";
1812 Out << "#include \n";
1813 Out << "#include \n";
1814 Out << "#include \n";
1815 Out << "#include \n";
1816 Out << "#include \n";
1817 Out << "#include \n";
1818 Out << "#include \n";
1819 Out << "#include \n";
1820 Out << "using namespace llvm;\n\n";
1821 Out << "Module* " << fname << "();\n\n";
1822 Out << "int main(int argc, char**argv) {\n";
1823 Out << " Module* Mod = " << fname << "();\n";
1824 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1825 Out << " PassManager PM;\n";
1826 Out << " PM.add(createPrintModulePass(&outs()));\n";
1827 Out << " PM.run(*Mod);\n";
1828 Out << " return 0;\n";
1829 Out << "}\n\n";
1830 printModule(fname,mName);
1831 }
1832
1833 void CppWriter::printModule(const std::string& fname,
1699 printInstruction(I,bbname);
1700 }
1701 }
1702
1703 // Loop over the ForwardRefs and resolve them now that all instructions
1704 // are generated.
1705 if (!ForwardRefs.empty()) {
1706 nl(Out) << "// Resolve Forward References";
1707 nl(Out);
1708 }
1709
1710 while (!ForwardRefs.empty()) {
1711 ForwardRefMap::iterator I = ForwardRefs.begin();
1712 Out << I->second << "->replaceAllUsesWith("
1713 << getCppName(I->first) << "); delete " << I->second << ";";
1714 nl(Out);
1715 ForwardRefs.erase(I);
1716 }
1717 }
1718
1719 void CppWriter::printInline(const std::string& fname,
1720 const std::string& func) {
1721 const Function* F = TheModule->getFunction(func);
1722 if (!F) {
1723 error(std::string("Function '") + func + "' not found in input module");
1724 return;
1725 }
1726 if (F->isDeclaration()) {
1727 error(std::string("Function '") + func + "' is external!");
1728 return;
1729 }
1730 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1731 << getCppName(F);
1732 unsigned arg_count = 1;
1733 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1734 AI != AE; ++AI) {
1735 Out << ", Value* arg_" << arg_count;
1736 }
1737 Out << ") {";
1738 nl(Out);
1739 is_inline = true;
1740 printFunctionUses(F);
1741 printFunctionBody(F);
1742 is_inline = false;
1743 Out << "return " << getCppName(F->begin()) << ";";
1744 nl(Out) << "}";
1745 nl(Out);
1746 }
1747
1748 void CppWriter::printModuleBody() {
1749 // Print out all the type definitions
1750 nl(Out) << "// Type Definitions"; nl(Out);
1751 printTypes(TheModule);
1752
1753 // Functions can call each other and global variables can reference them so
1754 // define all the functions first before emitting their function bodies.
1755 nl(Out) << "// Function Declarations"; nl(Out);
1756 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1757 I != E; ++I)
1758 printFunctionHead(I);
1759
1760 // Process the global variables declarations. We can't initialze them until
1761 // after the constants are printed so just print a header for each global
1762 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1763 for (Module::const_global_iterator I = TheModule->global_begin(),
1764 E = TheModule->global_end(); I != E; ++I) {
1765 printVariableHead(I);
1766 }
1767
1768 // Print out all the constants definitions. Constants don't recurse except
1769 // through GlobalValues. All GlobalValues have been declared at this point
1770 // so we can proceed to generate the constants.
1771 nl(Out) << "// Constant Definitions"; nl(Out);
1772 printConstants(TheModule);
1773
1774 // Process the global variables definitions now that all the constants have
1775 // been emitted. These definitions just couple the gvars with their constant
1776 // initializers.
1777 nl(Out) << "// Global Variable Definitions"; nl(Out);
1778 for (Module::const_global_iterator I = TheModule->global_begin(),
1779 E = TheModule->global_end(); I != E; ++I) {
1780 printVariableBody(I);
1781 }
1782
1783 // Finally, we can safely put out all of the function bodies.
1784 nl(Out) << "// Function Definitions"; nl(Out);
1785 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1786 I != E; ++I) {
1787 if (!I->isDeclaration()) {
1788 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1789 << ")";
1790 nl(Out) << "{";
1791 nl(Out,1);
1792 printFunctionBody(I);
1793 nl(Out,-1) << "}";
1794 nl(Out);
1795 }
1796 }
1797 }
1798
1799 void CppWriter::printProgram(const std::string& fname,
1800 const std::string& mName) {
1801 Out << "#include \n";
1802 Out << "#include \n";
1803 Out << "#include \n";
1804 Out << "#include \n";
1805 Out << "#include \n";
1806 Out << "#include \n";
1807 Out << "#include \n";
1808 Out << "#include \n";
1809 Out << "#include \n";
1810 Out << "#include \n";
1811 Out << "#include \n";
1812 Out << "#include \n";
1813 Out << "#include \n";
1814 Out << "#include \n";
1815 Out << "#include \n";
1816 Out << "#include \n";
1817 Out << "#include \n";
1818 Out << "#include \n";
1819 Out << "using namespace llvm;\n\n";
1820 Out << "Module* " << fname << "();\n\n";
1821 Out << "int main(int argc, char**argv) {\n";
1822 Out << " Module* Mod = " << fname << "();\n";
1823 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1824 Out << " PassManager PM;\n";
1825 Out << " PM.add(createPrintModulePass(&outs()));\n";
1826 Out << " PM.run(*Mod);\n";
1827 Out << " return 0;\n";
1828 Out << "}\n\n";
1829 printModule(fname,mName);
1830 }
1831
1832 void CppWriter::printModule(const std::string& fname,
1833 const std::string& mName) {
1834 nl(Out) << "Module* " << fname << "() {";
1835 nl(Out,1) << "// Module Construction";
1836 nl(Out) << "Module* mod = new Module(\"";
1837 printEscapedString(mName);
1838 Out << "\", getGlobalContext());";
1839 if (!TheModule->getTargetTriple().empty()) {
1840 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1841 }
1842 if (!TheModule->getTargetTriple().empty()) {
1843 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1844 << "\");";
1845 }
1846
1847 if (!TheModule->getModuleInlineAsm().empty()) {
1848 nl(Out) << "mod->setModuleInlineAsm(\"";
1849 printEscapedString(TheModule->getModuleInlineAsm());
1850 Out << "\");";
1851 }
1852 nl(Out);
1853
1854 // Loop over the dependent libraries and emit them.
1855 Module::lib_iterator LI = TheModule->lib_begin();
1856 Module::lib_iterator LE = TheModule->lib_end();
1857 while (LI != LE) {
1858 Out << "mod->addLibrary(\"" << *LI << "\");";
1859 nl(Out);
1860 ++LI;
1861 }
1862 printModuleBody();
1863 nl(Out) << "return mod;";
1864 nl(Out,-1) << "}";
1865 nl(Out);
1866 }
1867
1868 void CppWriter::printContents(const std::string& fname,
18341869 const std::string& mName) {
1835 nl(Out) << "Module* " << fname << "() {";
1836 nl(Out,1) << "// Module Construction";
1837 nl(Out) << "Module* mod = new Module(\"";
1838 printEscapedString(mName);
1839 Out << "\", getGlobalContext());";
1840 if (!TheModule->getTargetTriple().empty()) {
1841 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1842 }
1843 if (!TheModule->getTargetTriple().empty()) {
1844 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1845 << "\");";
1846 }
1847
1848 if (!TheModule->getModuleInlineAsm().empty()) {
1849 nl(Out) << "mod->setModuleInlineAsm(\"";
1850 printEscapedString(TheModule->getModuleInlineAsm());
1851 Out << "\");";
1852 }
1853 nl(Out);
1854
1855 // Loop over the dependent libraries and emit them.
1856 Module::lib_iterator LI = TheModule->lib_begin();
1857 Module::lib_iterator LE = TheModule->lib_end();
1858 while (LI != LE) {
1859 Out << "mod->addLibrary(\"" << *LI << "\");";
1860 nl(Out);
1861 ++LI;
1862 }
1863 printModuleBody();
1864 nl(Out) << "return mod;";
1865 nl(Out,-1) << "}";
1866 nl(Out);
1867 }
1868
1869 void CppWriter::printContents(const std::string& fname,
1870 const std::string& mName) {
1871 Out << "\nModule* " << fname << "(Module *mod) {\n";
1872 Out << "\nmod->setModuleIdentifier(\"";
1873 printEscapedString(mName);
1874 Out << "\");\n";
1875 printModuleBody();
1876 Out << "\nreturn mod;\n";
1877 Out << "\n}\n";
1878 }
1879
1880 void CppWriter::printFunction(const std::string& fname,
1881 const std::string& funcName) {
1882 const Function* F = TheModule->getFunction(funcName);
1883 if (!F) {
1884 error(std::string("Function '") + funcName + "' not found in input module");
1885 return;
1886 }
1887 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1888 printFunctionUses(F);
1889 printFunctionHead(F);
1890 printFunctionBody(F);
1891 Out << "return " << getCppName(F) << ";\n";
1892 Out << "}\n";
1893 }
1894
1895 void CppWriter::printFunctions() {
1896 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1897 Module::const_iterator I = funcs.begin();
1898 Module::const_iterator IE = funcs.end();
1899
1900 for (; I != IE; ++I) {
1901 const Function &func = *I;
1902 if (!func.isDeclaration()) {
1903 std::string name("define_");
1904 name += func.getName();
1905 printFunction(name, func.getName());
1906 }
1907 }
1908 }
1909
1910 void CppWriter::printVariable(const std::string& fname,
1911 const std::string& varName) {
1912 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1913
1914 if (!GV) {
1915 error(std::string("Variable '") + varName + "' not found in input module");
1916 return;
1917 }
1918 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1919 printVariableUses(GV);
1920 printVariableHead(GV);
1921 printVariableBody(GV);
1922 Out << "return " << getCppName(GV) << ";\n";
1923 Out << "}\n";
1924 }
1925
1926 void CppWriter::printType(const std::string& fname,
1927 const std::string& typeName) {
1928 const Type* Ty = TheModule->getTypeByName(typeName);
1929 if (!Ty) {
1930 error(std::string("Type '") + typeName + "' not found in input module");
1931 return;
1932 }
1933 Out << "\nType* " << fname << "(Module *mod) {\n";
1934 printType(Ty);
1935 Out << "return " << getCppName(Ty) << ";\n";
1936 Out << "}\n";
1937 }
1938
1939 bool CppWriter::runOnModule(Module &M) {
1940 TheModule = &M;
1941
1942 // Emit a header
1943 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1944
1945 // Get the name of the function we're supposed to generate
1946 std::string fname = FuncName.getValue();
1947
1948 // Get the name of the thing we are to generate
1949 std::string tgtname = NameToGenerate.getValue();
1950 if (GenerationType == GenModule ||
1951 GenerationType == GenContents ||
1952 GenerationType == GenProgram ||
1953 GenerationType == GenFunctions) {
1954 if (tgtname == "!bad!") {
1955 if (M.getModuleIdentifier() == "-")
1956 tgtname = "";
1957 else
1958 tgtname = M.getModuleIdentifier();
1959 }
1960 } else if (tgtname == "!bad!")
1961 error("You must use the -for option with -gen-{function,variable,type}");
1962
1963 switch (WhatToGenerate(GenerationType)) {
1964 case GenProgram:
1965 if (fname.empty())
1966 fname = "makeLLVMModule";
1967 printProgram(fname,tgtname);
1968 break;
1969 case GenModule:
1970 if (fname.empty())
1971 fname = "makeLLVMModule";
1972 printModule(fname,tgtname);
1973 break;
1974 case GenContents:
1975 if (fname.empty())
1976 fname = "makeLLVMModuleContents";
1977 printContents(fname,tgtname);
1978 break;
1979 case GenFunction:
1980 if (fname.empty())
1981 fname = "makeLLVMFunction";
1982 printFunction(fname,tgtname);
1983 break;
1984 case GenFunctions:
1985 printFunctions();
1986 break;
1987 case GenInline:
1988 if (fname.empty())
1989 fname = "makeLLVMInline";
1990 printInline(fname,tgtname);
1991 break;
1992 case GenVariable:
1993 if (fname.empty())
1994 fname = "makeLLVMVariable";
1995 printVariable(fname,tgtname);
1996 break;
1997 case GenType:
1998 if (fname.empty())
1999 fname = "makeLLVMType";
2000 printType(fname,tgtname);
2001 break;
2002 default:
2003 error("Invalid generation option");
2004 }
2005
2006 return false;
2007 }
1870 Out << "\nModule* " << fname << "(Module *mod) {\n";
1871 Out << "\nmod->setModuleIdentifier(\"";
1872 printEscapedString(mName);
1873 Out << "\");\n";
1874 printModuleBody();
1875 Out << "\nreturn mod;\n";
1876 Out << "\n}\n";
1877 }
1878
1879 void CppWriter::printFunction(const std::string& fname,
1880 const std::string& funcName) {
1881 const Function* F = TheModule->getFunction(funcName);
1882 if (!F) {
1883 error(std::string("Function '") + funcName + "' not found in input module");
1884 return;
1885 }
1886 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1887 printFunctionUses(F);
1888 printFunctionHead(F);
1889 printFunctionBody(F);
1890 Out << "return " << getCppName(F) << ";\n";
1891 Out << "}\n";
1892 }
1893
1894