blob: 15d16ecfe9d315eef68ae3d5ae58c80e7deb184e [file] [log] [blame]
Chris Lattner31c2ec32007-05-06 20:31:17 +00001//===-- MSILWriter.cpp - Library for converting LLVM code to MSIL ---------===//
Anton Korobeynikov099883f2007-03-21 21:38:25 +00002//
Bill Wendling85db3a92008-02-26 10:57:23 +00003// The LLVM Compiler Infrastructure
Anton Korobeynikov099883f2007-03-21 21:38:25 +00004//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This library converts LLVM code to MSIL code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MSILWriter.h"
15#include "llvm/CallingConv.h"
16#include "llvm/DerivedTypes.h"
17#include "llvm/Intrinsics.h"
18#include "llvm/IntrinsicInst.h"
19#include "llvm/TypeSymbolTable.h"
20#include "llvm/Analysis/ConstantsScanner.h"
21#include "llvm/Support/CallSite.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000022#include "llvm/Support/ErrorHandling.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000023#include "llvm/Support/InstVisitor.h"
Anton Korobeynikovf13090c2007-05-06 20:13:33 +000024#include "llvm/Support/MathExtras.h"
Daniel Dunbar0c795d62009-07-25 06:49:55 +000025#include "llvm/Target/TargetRegistry.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000026#include "llvm/Transforms/Scalar.h"
27#include "llvm/ADT/StringExtras.h"
Gordon Henriksence224772008-01-07 01:30:38 +000028#include "llvm/CodeGen/Passes.h"
Nick Lewycky92fbbc72009-07-26 08:16:51 +000029using namespace llvm;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000030
Nick Lewycky92fbbc72009-07-26 08:16:51 +000031namespace llvm {
Anton Korobeynikov099883f2007-03-21 21:38:25 +000032 // TargetMachine for the MSIL
Nick Lewycky6726b6d2009-10-25 06:33:48 +000033 struct MSILTarget : public TargetMachine {
Daniel Dunbar214e2232009-08-04 04:02:45 +000034 MSILTarget(const Target &T, const std::string &TT, const std::string &FS)
35 : TargetMachine(T) {}
Anton Korobeynikov099883f2007-03-21 21:38:25 +000036
37 virtual bool WantsWholeFile() const { return true; }
David Greene71847812009-07-14 20:18:05 +000038 virtual bool addPassesToEmitWholeFile(PassManager &PM,
39 formatted_raw_ostream &Out,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000040 CodeGenFileType FileType,
Dan Gohman8772f502010-02-28 00:41:59 +000041 CodeGenOpt::Level OptLevel,
42 bool DisableVerify);
Anton Korobeynikov099883f2007-03-21 21:38:25 +000043
Daniel Dunbard1a919e2009-08-03 17:40:25 +000044 virtual const TargetData *getTargetData() const { return 0; }
Anton Korobeynikov099883f2007-03-21 21:38:25 +000045 };
46}
47
Daniel Dunbar0c795d62009-07-25 06:49:55 +000048extern "C" void LLVMInitializeMSILTarget() {
49 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000050 RegisterTargetMachine<MSILTarget> X(TheMSILTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000051}
Douglas Gregor1555a232009-06-16 20:12:29 +000052
Anton Korobeynikov099883f2007-03-21 21:38:25 +000053bool MSILModule::runOnModule(Module &M) {
54 ModulePtr = &M;
55 TD = &getAnalysis<TargetData>();
56 bool Changed = false;
57 // Find named types.
58 TypeSymbolTable& Table = M.getTypeSymbolTable();
59 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
60 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
Duncan Sands47c51882010-02-16 14:50:09 +000061 if (!I->second->isStructTy() && !I->second->isOpaqueTy())
Anton Korobeynikov099883f2007-03-21 21:38:25 +000062 Table.remove(I++);
63 else {
64 std::set<const Type *>::iterator T = Types.find(I->second);
65 if (T==Types.end())
66 Table.remove(I++);
67 else {
68 Types.erase(T);
69 ++I;
70 }
71 }
72 }
73 // Find unnamed types.
74 unsigned RenameCounter = 0;
75 for (std::set<const Type *>::const_iterator I = Types.begin(),
76 E = Types.end(); I!=E; ++I)
77 if (const StructType *STy = dyn_cast<StructType>(*I)) {
78 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
79 ++RenameCounter;
80 Changed = true;
81 }
82 // Pointer for FunctionPass.
83 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
84 return Changed;
85}
86
Devang Patel19974732007-05-03 01:11:54 +000087char MSILModule::ID = 0;
88char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000089
90bool MSILWriter::runOnFunction(Function &F) {
91 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +000092
93 // Do not codegen any 'available_externally' functions at all, they have
94 // definitions outside the translation unit.
95 if (F.hasAvailableExternallyLinkage())
96 return false;
97
Anton Korobeynikov099883f2007-03-21 21:38:25 +000098 LInfo = &getAnalysis<LoopInfo>();
99 printFunction(F);
100 return false;
101}
102
103
104bool MSILWriter::doInitialization(Module &M) {
105 ModulePtr = &M;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000106 Out << ".assembly extern mscorlib {}\n";
107 Out << ".assembly MSIL {}\n\n";
108 Out << "// External\n";
109 printExternals();
110 Out << "// Declarations\n";
111 printDeclarations(M.getTypeSymbolTable());
112 Out << "// Definitions\n";
113 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000114 Out << "// Startup code\n";
115 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000116 return false;
117}
118
119
120bool MSILWriter::doFinalization(Module &M) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000121 return false;
122}
123
124
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000125void MSILWriter::printModuleStartup() {
126 Out <<
127 ".method static public int32 $MSIL_Startup() {\n"
128 "\t.entrypoint\n"
129 "\t.locals (native int i)\n"
130 "\t.locals (native int argc)\n"
131 "\t.locals (native int ptr)\n"
132 "\t.locals (void* argv)\n"
133 "\t.locals (string[] args)\n"
134 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
135 "\tdup\n"
136 "\tstloc\targs\n"
137 "\tldlen\n"
138 "\tconv.i4\n"
139 "\tdup\n"
140 "\tstloc\targc\n";
141 printPtrLoad(TD->getPointerSize());
142 Out <<
143 "\tmul\n"
144 "\tlocalloc\n"
145 "\tstloc\targv\n"
146 "\tldc.i4.0\n"
147 "\tstloc\ti\n"
148 "L_01:\n"
149 "\tldloc\ti\n"
150 "\tldloc\targc\n"
151 "\tceq\n"
152 "\tbrtrue\tL_02\n"
153 "\tldloc\targs\n"
154 "\tldloc\ti\n"
155 "\tldelem.ref\n"
156 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
157 "StringToHGlobalAnsi(string)\n"
158 "\tstloc\tptr\n"
159 "\tldloc\targv\n"
160 "\tldloc\ti\n";
161 printPtrLoad(TD->getPointerSize());
162 Out <<
163 "\tmul\n"
164 "\tadd\n"
165 "\tldloc\tptr\n"
166 "\tstind.i\n"
167 "\tldloc\ti\n"
168 "\tldc.i4.1\n"
169 "\tadd\n"
170 "\tstloc\ti\n"
171 "\tbr\tL_01\n"
172 "L_02:\n"
173 "\tcall void $MSIL_Init()\n";
174
175 // Call user 'main' function.
176 const Function* F = ModulePtr->getFunction("main");
177 if (!F || F->isDeclaration()) {
178 Out << "\tldc.i4.0\n\tret\n}\n";
179 return;
180 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000181 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000182 std::string Args("");
183 Function::const_arg_iterator Arg1,Arg2;
184
185 switch (F->arg_size()) {
186 case 0:
187 BadSig = false;
188 break;
189 case 1:
190 Arg1 = F->arg_begin();
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000191 if (Arg1->getType()->isIntegerTy()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000192 Out << "\tldloc\targc\n";
193 Args = getTypeName(Arg1->getType());
194 BadSig = false;
195 }
196 break;
197 case 2:
198 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000199 if (Arg1->getType()->isIntegerTy() &&
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000200 Arg2->getType()->getTypeID() == Type::PointerTyID) {
201 Out << "\tldloc\targc\n\tldloc\targv\n";
202 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
203 BadSig = false;
204 }
205 break;
206 default:
207 BadSig = true;
208 }
209
210 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000211 if (BadSig || (!F->getReturnType()->isIntegerTy() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000212 Out << "\tldc.i4.0\n";
213 } else {
214 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
215 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
216 if (RetVoid)
217 Out << "\tldc.i4.0\n";
218 else
219 Out << "\tconv.i4\n";
220 }
221 Out << "\tret\n}\n";
222}
223
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000224bool MSILWriter::isZeroValue(const Value* V) {
225 if (const Constant *C = dyn_cast<Constant>(V))
226 return C->isNullValue();
227 return false;
228}
229
230
231std::string MSILWriter::getValueName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000232 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000233 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattner27891032010-01-16 02:15:38 +0000234 Name = GV->getName();
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000235 else {
236 unsigned &No = AnonValueNumbers[V];
237 if (No == 0) No = ++NextAnonValueNumber;
238 Name = "tmp" + utostr(No);
239 }
240
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000241 // Name into the quotes allow control and space characters.
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000242 return "'"+Name+"'";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000243}
244
245
246std::string MSILWriter::getLabelName(const std::string& Name) {
247 if (Name.find('.')!=std::string::npos) {
248 std::string Tmp(Name);
249 // Replace unaccepable characters in the label name.
250 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
251 if (*I=='.') *I = '@';
252 return Tmp;
253 }
254 return Name;
255}
256
257
258std::string MSILWriter::getLabelName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000259 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000260 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattner27891032010-01-16 02:15:38 +0000261 Name = GV->getName();
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000262 else {
263 unsigned &No = AnonValueNumbers[V];
264 if (No == 0) No = ++NextAnonValueNumber;
265 Name = "tmp" + utostr(No);
266 }
267
268 return getLabelName(Name);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000269}
270
271
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000272std::string MSILWriter::getConvModopt(CallingConv::ID CallingConvID) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000273 switch (CallingConvID) {
274 case CallingConv::C:
275 case CallingConv::Cold:
276 case CallingConv::Fast:
277 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
278 case CallingConv::X86_FastCall:
279 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
280 case CallingConv::X86_StdCall:
281 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
282 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000283 errs() << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000284 llvm_unreachable("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000285 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000286 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000287}
288
289
290std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
291 std::string Tmp = "";
292 const Type* ElemTy = Ty;
293 assert(Ty->getTypeID()==TyID && "Invalid type passed");
294 // Walk trought array element types.
295 for (;;) {
296 // Multidimensional array.
297 if (ElemTy->getTypeID()==TyID) {
298 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
299 Tmp += utostr(ATy->getNumElements());
300 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
301 Tmp += utostr(VTy->getNumElements());
302 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
303 }
304 // Base element type found.
305 if (ElemTy->getTypeID()!=TyID) break;
306 Tmp += ",";
307 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000308 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000309}
310
311
312std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
313 unsigned NumBits = 0;
314 switch (Ty->getTypeID()) {
315 case Type::VoidTyID:
316 return "void ";
317 case Type::IntegerTyID:
318 NumBits = getBitWidth(Ty);
319 if(NumBits==1)
320 return "bool ";
321 if (!isSigned)
322 return "unsigned int"+utostr(NumBits)+" ";
323 return "int"+utostr(NumBits)+" ";
324 case Type::FloatTyID:
325 return "float32 ";
326 case Type::DoubleTyID:
327 return "float64 ";
328 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000329 errs() << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000330 llvm_unreachable("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000331 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000332 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000333}
334
335
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000336std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
337 bool isNested) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000338 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000339 return getPrimitiveTypeName(Ty,isSigned);
340 // FIXME: "OpaqueType" support
341 switch (Ty->getTypeID()) {
342 case Type::PointerTyID:
343 return "void* ";
344 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000345 if (isNested)
346 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000347 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
348 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000349 if (isNested)
350 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000351 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
352 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000353 if (isNested)
354 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000355 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
356 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000357 errs() << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000358 llvm_unreachable("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000359 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000360 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000361}
362
363
364MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
365 // Function argument
366 if (isa<Argument>(V))
367 return ArgumentVT;
368 // Function
369 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000370 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000371 // Variable
372 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000373 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000374 // Constant
375 else if (isa<Constant>(V))
376 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
377 // Local variable
378 return LocalVT;
379}
380
381
382std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
383 bool isSigned) {
384 unsigned NumBits = 0;
385 switch (Ty->getTypeID()) {
386 // Integer constant, expanding for stack operations.
387 case Type::IntegerTyID:
388 NumBits = getBitWidth(Ty);
389 // Expand integer value to "int32" or "int64".
390 if (Expand) return (NumBits<=32 ? "i4" : "i8");
391 if (NumBits==1) return "i1";
392 return (isSigned ? "i" : "u")+utostr(NumBits/8);
393 // Float constant.
394 case Type::FloatTyID:
395 return "r4";
396 case Type::DoubleTyID:
397 return "r8";
398 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000399 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000400 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000401 errs() << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000402 llvm_unreachable("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000403 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000404 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000405}
406
407
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000408void MSILWriter::printConvToPtr() {
409 switch (ModulePtr->getPointerSize()) {
410 case Module::Pointer32:
411 printSimpleInstruction("conv.u4");
412 break;
413 case Module::Pointer64:
414 printSimpleInstruction("conv.u8");
415 break;
416 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000417 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000418 }
419}
420
421
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000422void MSILWriter::printPtrLoad(uint64_t N) {
423 switch (ModulePtr->getPointerSize()) {
424 case Module::Pointer32:
425 printSimpleInstruction("ldc.i4",utostr(N).c_str());
426 // FIXME: Need overflow test?
Benjamin Kramer34247a02010-03-29 21:13:41 +0000427 if (!isUInt<32>(N)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000428 errs() << "Value = " << utostr(N) << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000429 llvm_unreachable("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000430 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000431 break;
432 case Module::Pointer64:
433 printSimpleInstruction("ldc.i8",utostr(N).c_str());
434 break;
435 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000436 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000437 }
438}
439
440
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000441void MSILWriter::printValuePtrLoad(const Value* V) {
442 printValueLoad(V);
443 printConvToPtr();
444}
445
446
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000447void MSILWriter::printConstLoad(const Constant* C) {
448 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
449 // Integer constant
450 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
451 if (CInt->isMinValue(true))
452 Out << CInt->getSExtValue();
453 else
454 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000455 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000456 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000457 uint64_t X;
458 unsigned Size;
459 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000460 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000461 Size = 4;
462 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000463 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000464 Size = 8;
465 }
466 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
467 } else if (isa<UndefValue>(C)) {
468 // Undefined constant value = NULL.
469 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000470 } else {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000471 errs() << "Constant = " << *C << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000472 llvm_unreachable("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000473 }
474 Out << '\n';
475}
476
477
478void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000479 MSILWriter::ValueType Location = getValueLocation(V);
480 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000481 // Global variable or function address.
482 case GlobalVT:
483 case InternalVT:
484 if (const Function* F = dyn_cast<Function>(V)) {
485 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
486 printSimpleInstruction("ldftn",
487 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
488 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000489 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000490 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000491 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
492 Tmp = "void* "+getValueName(V);
493 printSimpleInstruction("ldsfld",Tmp.c_str());
494 } else {
495 Tmp = getTypeName(ElemTy)+getValueName(V);
496 printSimpleInstruction("ldsflda",Tmp.c_str());
497 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000498 }
499 break;
500 // Function argument.
501 case ArgumentVT:
502 printSimpleInstruction("ldarg",getValueName(V).c_str());
503 break;
504 // Local function variable.
505 case LocalVT:
506 printSimpleInstruction("ldloc",getValueName(V).c_str());
507 break;
508 // Constant value.
509 case ConstVT:
510 if (isa<ConstantPointerNull>(V))
511 printPtrLoad(0);
512 else
513 printConstLoad(cast<Constant>(V));
514 break;
515 // Constant expression.
516 case ConstExprVT:
517 printConstantExpr(cast<ConstantExpr>(V));
518 break;
519 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000520 errs() << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000521 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000522 }
523}
524
525
526void MSILWriter::printValueSave(const Value* V) {
527 switch (getValueLocation(V)) {
528 case ArgumentVT:
529 printSimpleInstruction("starg",getValueName(V).c_str());
530 break;
531 case LocalVT:
532 printSimpleInstruction("stloc",getValueName(V).c_str());
533 break;
534 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000535 errs() << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000536 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000537 }
538}
539
540
541void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
542 const Value* Right) {
543 printValueLoad(Left);
544 printValueLoad(Right);
545 Out << '\t' << Name << '\n';
546}
547
548
549void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
550 if(Operand)
551 Out << '\t' << Inst << '\t' << Operand << '\n';
552 else
553 Out << '\t' << Inst << '\n';
554}
555
556
557void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
Bill Wendling3ef10852009-12-28 01:42:12 +0000558 for (BasicBlock::const_iterator I = Dst->begin(); isa<PHINode>(I); ++I) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000559 const PHINode* Phi = cast<PHINode>(I);
560 const Value* Val = Phi->getIncomingValueForBlock(Src);
561 if (isa<UndefValue>(Val)) continue;
562 printValueLoad(Val);
563 printValueSave(Phi);
564 }
565}
566
567
568void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
569 const BasicBlock* TrueBB,
570 const BasicBlock* FalseBB) {
571 if (TrueBB==FalseBB) {
572 // "TrueBB" and "FalseBB" destination equals
573 printPHICopy(CurrBB,TrueBB);
574 printSimpleInstruction("pop");
575 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
576 } else if (FalseBB==NULL) {
577 // If "FalseBB" not used the jump have condition
578 printPHICopy(CurrBB,TrueBB);
579 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
580 } else if (TrueBB==NULL) {
581 // If "TrueBB" not used the jump is unconditional
582 printPHICopy(CurrBB,FalseBB);
583 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
584 } else {
585 // Copy PHI instructions for each block
586 std::string TmpLabel;
587 // Print PHI instructions for "TrueBB"
588 if (isa<PHINode>(TrueBB->begin())) {
589 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
590 printSimpleInstruction("brtrue",TmpLabel.c_str());
591 } else {
592 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
593 }
594 // Print PHI instructions for "FalseBB"
595 if (isa<PHINode>(FalseBB->begin())) {
596 printPHICopy(CurrBB,FalseBB);
597 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
598 } else {
599 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
600 }
601 if (isa<PHINode>(TrueBB->begin())) {
602 // Handle "TrueBB" PHI Copy
603 Out << TmpLabel << ":\n";
604 printPHICopy(CurrBB,TrueBB);
605 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
606 }
607 }
608}
609
610
611void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
612 if (Inst->isUnconditional()) {
613 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
614 } else {
615 printValueLoad(Inst->getCondition());
616 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
617 Inst->getSuccessor(1));
618 }
619}
620
621
622void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
623 const Value* VFalse) {
624 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
625 printValueLoad(VTrue);
626 printValueLoad(Cond);
627 printSimpleInstruction("brtrue",TmpLabel.c_str());
628 printSimpleInstruction("pop");
629 printValueLoad(VFalse);
630 Out << TmpLabel << ":\n";
631}
632
633
634void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000635 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000636 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000637 if (const PointerType* P = dyn_cast<PointerType>(Ty))
638 Ty = P->getElementType();
639 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000640 printSimpleInstruction(Tmp.c_str());
641}
642
643
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000644void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000645 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000646 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000647 printIndirectSave(Val->getType());
648}
649
650
651void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000652 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000653 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000654 if (*postfix.begin()=='u') *postfix.begin() = 'i';
655 postfix = "stind."+postfix;
656 printSimpleInstruction(postfix.c_str());
657}
658
659
660void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000661 const Type* Ty, const Type* SrcTy) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000662 std::string Tmp("");
663 printValueLoad(V);
664 switch (Op) {
665 // Signed
666 case Instruction::SExt:
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000667 // If sign extending int, convert first from unsigned to signed
668 // with the same bit size - because otherwise we will loose the sign.
669 if (SrcTy) {
670 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
671 printSimpleInstruction(Tmp.c_str());
672 }
Bill Wendling5f544502009-07-14 18:30:04 +0000673 // FALLTHROUGH
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000674 case Instruction::SIToFP:
675 case Instruction::FPToSI:
676 Tmp = "conv."+getTypePostfix(Ty,false,true);
677 printSimpleInstruction(Tmp.c_str());
678 break;
679 // Unsigned
680 case Instruction::FPTrunc:
681 case Instruction::FPExt:
682 case Instruction::UIToFP:
683 case Instruction::Trunc:
684 case Instruction::ZExt:
685 case Instruction::FPToUI:
686 case Instruction::PtrToInt:
687 case Instruction::IntToPtr:
688 Tmp = "conv."+getTypePostfix(Ty,false);
689 printSimpleInstruction(Tmp.c_str());
690 break;
691 // Do nothing
692 case Instruction::BitCast:
693 // FIXME: meaning that ld*/st* instruction do not change data format.
694 break;
695 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000696 errs() << "Opcode = " << Op << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000697 llvm_unreachable("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000698 }
699}
700
701
702void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
703 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000704 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000705 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000706 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000707 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000708 for (; I!=E; ++I){
709 Size = 0;
710 const Value* IndexValue = I.getOperand();
711 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
712 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
713 // Offset is the sum of all previous structure fields.
714 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000715 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000716 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000717 printSimpleInstruction("add");
718 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000719 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000720 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000721 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000722 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000723 }
724 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000725 if (!isZeroValue(IndexValue)) {
726 // Constant optimization.
727 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
728 if (C->getValue().isNegative()) {
729 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
730 printSimpleInstruction("sub");
731 continue;
732 } else
733 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000734 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000735 printPtrLoad(Size);
736 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000737 printSimpleInstruction("mul");
738 }
739 printSimpleInstruction("add");
740 }
741 }
742}
743
744
745std::string MSILWriter::getCallSignature(const FunctionType* Ty,
746 const Instruction* Inst,
747 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000748 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000749 if (Ty->isVarArg()) Tmp += "vararg ";
750 // Name and return type.
751 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
752 // Function argument type list.
753 unsigned NumParams = Ty->getNumParams();
754 for (unsigned I = 0; I!=NumParams; ++I) {
755 if (I!=0) Tmp += ",";
756 Tmp += getTypeName(Ty->getParamType(I));
757 }
758 // CLR needs to know the exact amount of parameters received by vararg
759 // function, because caller cleans the stack.
760 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000761 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000762 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
763 // Print variable argument types.
764 unsigned NumOperands = Inst->getNumOperands()-Org;
765 if (NumParams<NumOperands) {
766 if (NumParams!=0) Tmp += ", ";
767 Tmp += "... , ";
768 for (unsigned J = NumParams; J!=NumOperands; ++J) {
769 if (J!=NumParams) Tmp += ", ";
770 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
771 }
772 }
773 }
774 return Tmp+")";
775}
776
777
778void MSILWriter::printFunctionCall(const Value* FnVal,
779 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000780 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000781 std::string Name = "";
782 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
783 Name = getConvModopt(Call->getCallingConv());
784 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
785 Name = getConvModopt(Invoke->getCallingConv());
786 else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000787 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000788 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000789 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000790 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000791 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000792 Name += getValueName(F);
793 printSimpleInstruction("call",
794 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
795 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000796 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000797 const PointerType* PTy = cast<PointerType>(FnVal->getType());
798 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000799 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000800 printValueLoad(FnVal);
801 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
802 }
803}
804
805
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000806void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
807 std::string Name;
808 switch (Inst->getIntrinsicID()) {
809 case Intrinsic::vastart:
810 Name = getValueName(Inst->getOperand(1));
811 Name.insert(Name.length()-1,"$valist");
812 // Obtain the argument handle.
813 printSimpleInstruction("ldloca",Name.c_str());
814 printSimpleInstruction("arglist");
815 printSimpleInstruction("call",
816 "instance void [mscorlib]System.ArgIterator::.ctor"
817 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
818 // Save as pointer type "void*"
819 printValueLoad(Inst->getOperand(1));
820 printSimpleInstruction("ldloca",Name.c_str());
Owen Anderson1d0be152009-08-13 21:58:54 +0000821 printIndirectSave(PointerType::getUnqual(
822 IntegerType::get(Inst->getContext(), 8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000823 break;
824 case Intrinsic::vaend:
825 // Close argument list handle.
826 printIndirectLoad(Inst->getOperand(1));
827 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
828 break;
829 case Intrinsic::vacopy:
830 // Copy "ArgIterator" valuetype.
831 printIndirectLoad(Inst->getOperand(1));
832 printIndirectLoad(Inst->getOperand(2));
833 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
834 break;
835 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000836 errs() << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000837 llvm_unreachable("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000838 }
839}
840
841
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000842void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000843 if (isa<IntrinsicInst>(Inst)) {
844 // Handle intrinsic function.
845 printIntrinsicCall(cast<IntrinsicInst>(Inst));
846 } else {
847 // Load arguments to stack and call function.
848 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
849 printValueLoad(Inst->getOperand(I));
850 printFunctionCall(Inst->getOperand(0),Inst);
851 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000852}
853
854
855void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
856 const Value* Right) {
857 switch (Predicate) {
858 case ICmpInst::ICMP_EQ:
859 printBinaryInstruction("ceq",Left,Right);
860 break;
861 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000862 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000863 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000864 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000865 printSimpleInstruction("not");
866 break;
867 case ICmpInst::ICMP_ULE:
868 case ICmpInst::ICMP_SLE:
869 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
870 printBinaryInstruction("ceq",Left,Right);
871 if (Predicate==ICmpInst::ICMP_ULE)
872 printBinaryInstruction("clt.un",Left,Right);
873 else
874 printBinaryInstruction("clt",Left,Right);
875 printSimpleInstruction("or");
876 break;
877 case ICmpInst::ICMP_UGE:
878 case ICmpInst::ICMP_SGE:
879 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
880 printBinaryInstruction("ceq",Left,Right);
881 if (Predicate==ICmpInst::ICMP_UGE)
882 printBinaryInstruction("cgt.un",Left,Right);
883 else
884 printBinaryInstruction("cgt",Left,Right);
885 printSimpleInstruction("or");
886 break;
887 case ICmpInst::ICMP_ULT:
888 printBinaryInstruction("clt.un",Left,Right);
889 break;
890 case ICmpInst::ICMP_SLT:
891 printBinaryInstruction("clt",Left,Right);
892 break;
893 case ICmpInst::ICMP_UGT:
894 printBinaryInstruction("cgt.un",Left,Right);
Anton Korobeynikove9fd67e2009-07-14 09:52:47 +0000895 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000896 case ICmpInst::ICMP_SGT:
897 printBinaryInstruction("cgt",Left,Right);
898 break;
899 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000900 errs() << "Predicate = " << Predicate << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000901 llvm_unreachable("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000902 }
903}
904
905
906void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
907 const Value* Right) {
908 // FIXME: Correct comparison
909 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
910 switch (Predicate) {
911 case FCmpInst::FCMP_UGT:
912 // X > Y || llvm_fcmp_uno(X, Y)
913 printBinaryInstruction("cgt",Left,Right);
914 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
915 printSimpleInstruction("or");
916 break;
917 case FCmpInst::FCMP_OGT:
918 // X > Y
919 printBinaryInstruction("cgt",Left,Right);
920 break;
921 case FCmpInst::FCMP_UGE:
922 // X >= Y || llvm_fcmp_uno(X, Y)
923 printBinaryInstruction("ceq",Left,Right);
924 printBinaryInstruction("cgt",Left,Right);
925 printSimpleInstruction("or");
926 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
927 printSimpleInstruction("or");
928 break;
929 case FCmpInst::FCMP_OGE:
930 // X >= Y
931 printBinaryInstruction("ceq",Left,Right);
932 printBinaryInstruction("cgt",Left,Right);
933 printSimpleInstruction("or");
934 break;
935 case FCmpInst::FCMP_ULT:
936 // X < Y || llvm_fcmp_uno(X, Y)
937 printBinaryInstruction("clt",Left,Right);
938 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
939 printSimpleInstruction("or");
940 break;
941 case FCmpInst::FCMP_OLT:
942 // X < Y
943 printBinaryInstruction("clt",Left,Right);
944 break;
945 case FCmpInst::FCMP_ULE:
946 // X <= Y || llvm_fcmp_uno(X, Y)
947 printBinaryInstruction("ceq",Left,Right);
948 printBinaryInstruction("clt",Left,Right);
949 printSimpleInstruction("or");
950 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
951 printSimpleInstruction("or");
952 break;
953 case FCmpInst::FCMP_OLE:
954 // X <= Y
955 printBinaryInstruction("ceq",Left,Right);
956 printBinaryInstruction("clt",Left,Right);
957 printSimpleInstruction("or");
958 break;
959 case FCmpInst::FCMP_UEQ:
960 // X == Y || llvm_fcmp_uno(X, Y)
961 printBinaryInstruction("ceq",Left,Right);
962 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
963 printSimpleInstruction("or");
964 break;
965 case FCmpInst::FCMP_OEQ:
966 // X == Y
967 printBinaryInstruction("ceq",Left,Right);
968 break;
969 case FCmpInst::FCMP_UNE:
970 // X != Y
971 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000972 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000973 printSimpleInstruction("not");
974 break;
975 case FCmpInst::FCMP_ONE:
976 // X != Y && llvm_fcmp_ord(X, Y)
977 printBinaryInstruction("ceq",Left,Right);
978 printSimpleInstruction("not");
979 break;
980 case FCmpInst::FCMP_ORD:
981 // return X == X && Y == Y
982 printBinaryInstruction("ceq",Left,Left);
983 printBinaryInstruction("ceq",Right,Right);
984 printSimpleInstruction("or");
985 break;
986 case FCmpInst::FCMP_UNO:
987 // X != X || Y != Y
988 printBinaryInstruction("ceq",Left,Left);
989 printSimpleInstruction("not");
990 printBinaryInstruction("ceq",Right,Right);
991 printSimpleInstruction("not");
992 printSimpleInstruction("or");
993 break;
994 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000995 llvm_unreachable("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000996 }
997}
998
999
1000void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1001 std::string Label = "leave$normal_"+utostr(getUniqID());
1002 Out << ".try {\n";
1003 // Load arguments
1004 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1005 printValueLoad(Inst->getOperand(I));
1006 // Print call instruction
1007 printFunctionCall(Inst->getOperand(0),Inst);
1008 // Save function result and leave "try" block
1009 printValueSave(Inst);
1010 printSimpleInstruction("leave",Label.c_str());
1011 Out << "}\n";
1012 Out << "catch [mscorlib]System.Exception {\n";
1013 // Redirect to unwind block
1014 printSimpleInstruction("pop");
1015 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1016 Out << "}\n" << Label << ":\n";
1017 // Redirect to continue block
1018 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1019}
1020
1021
1022void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1023 // FIXME: Emulate with IL "switch" instruction
1024 // Emulate = if () else if () else if () else ...
1025 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1026 printValueLoad(Inst->getCondition());
1027 printValueLoad(Inst->getCaseValue(I));
1028 printSimpleInstruction("ceq");
1029 // Condition jump to successor block
1030 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1031 }
1032 // Jump to default block
1033 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1034}
1035
1036
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001037void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1038 printIndirectLoad(Inst->getOperand(0));
1039 printSimpleInstruction("call",
1040 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1041 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001042 std::string Name =
Owen Anderson1d0be152009-08-13 21:58:54 +00001043 "ldind."+getTypePostfix(PointerType::getUnqual(
1044 IntegerType::get(Inst->getContext(), 8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001045 printSimpleInstruction(Name.c_str());
1046}
1047
1048
1049void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sands777d2302009-05-09 07:06:46 +00001050 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001051 // Constant optimization.
1052 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1053 printPtrLoad(CInt->getZExtValue()*Size);
1054 } else {
1055 printPtrLoad(Size);
1056 printValueLoad(Inst->getOperand(0));
1057 printSimpleInstruction("mul");
1058 }
1059 printSimpleInstruction("localloc");
1060}
1061
1062
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001063void MSILWriter::printInstruction(const Instruction* Inst) {
1064 const Value *Left = 0, *Right = 0;
1065 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1066 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1067 // Print instruction
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001068 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001069 switch (Inst->getOpcode()) {
1070 // Terminator
1071 case Instruction::Ret:
1072 if (Inst->getNumOperands()) {
1073 printValueLoad(Left);
1074 printSimpleInstruction("ret");
1075 } else
1076 printSimpleInstruction("ret");
1077 break;
1078 case Instruction::Br:
1079 printBranchInstruction(cast<BranchInst>(Inst));
1080 break;
1081 // Binary
1082 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001083 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001084 printBinaryInstruction("add",Left,Right);
1085 break;
1086 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001087 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001088 printBinaryInstruction("sub",Left,Right);
1089 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001090 case Instruction::Mul:
1091 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001092 printBinaryInstruction("mul",Left,Right);
1093 break;
1094 case Instruction::UDiv:
1095 printBinaryInstruction("div.un",Left,Right);
1096 break;
1097 case Instruction::SDiv:
1098 case Instruction::FDiv:
1099 printBinaryInstruction("div",Left,Right);
1100 break;
1101 case Instruction::URem:
1102 printBinaryInstruction("rem.un",Left,Right);
1103 break;
1104 case Instruction::SRem:
1105 case Instruction::FRem:
1106 printBinaryInstruction("rem",Left,Right);
1107 break;
1108 // Binary Condition
1109 case Instruction::ICmp:
1110 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1111 break;
1112 case Instruction::FCmp:
1113 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1114 break;
1115 // Bitwise Binary
1116 case Instruction::And:
1117 printBinaryInstruction("and",Left,Right);
1118 break;
1119 case Instruction::Or:
1120 printBinaryInstruction("or",Left,Right);
1121 break;
1122 case Instruction::Xor:
1123 printBinaryInstruction("xor",Left,Right);
1124 break;
1125 case Instruction::Shl:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001126 printValueLoad(Left);
1127 printValueLoad(Right);
1128 printSimpleInstruction("conv.i4");
1129 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001130 break;
1131 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001132 printValueLoad(Left);
1133 printValueLoad(Right);
1134 printSimpleInstruction("conv.i4");
1135 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001136 break;
1137 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001138 printValueLoad(Left);
1139 printValueLoad(Right);
1140 printSimpleInstruction("conv.i4");
1141 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001142 break;
1143 case Instruction::Select:
1144 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1145 break;
1146 case Instruction::Load:
1147 printIndirectLoad(Inst->getOperand(0));
1148 break;
1149 case Instruction::Store:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001150 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001151 break;
Anton Korobeynikov94ac0342009-07-14 09:53:14 +00001152 case Instruction::SExt:
1153 printCastInstruction(Inst->getOpcode(),Left,
1154 cast<CastInst>(Inst)->getDestTy(),
1155 cast<CastInst>(Inst)->getSrcTy());
1156 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001157 case Instruction::Trunc:
1158 case Instruction::ZExt:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001159 case Instruction::FPTrunc:
1160 case Instruction::FPExt:
1161 case Instruction::UIToFP:
1162 case Instruction::SIToFP:
1163 case Instruction::FPToUI:
1164 case Instruction::FPToSI:
1165 case Instruction::PtrToInt:
1166 case Instruction::IntToPtr:
1167 case Instruction::BitCast:
1168 printCastInstruction(Inst->getOpcode(),Left,
1169 cast<CastInst>(Inst)->getDestTy());
1170 break;
1171 case Instruction::GetElementPtr:
1172 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1173 gep_type_end(Inst));
1174 break;
1175 case Instruction::Call:
1176 printCallInstruction(cast<CallInst>(Inst));
1177 break;
1178 case Instruction::Invoke:
1179 printInvokeInstruction(cast<InvokeInst>(Inst));
1180 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001181 case Instruction::Unwind:
1182 printSimpleInstruction("newobj",
1183 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001184 printSimpleInstruction("throw");
1185 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001186 case Instruction::Switch:
1187 printSwitchInstruction(cast<SwitchInst>(Inst));
1188 break;
1189 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001190 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001191 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001192 case Instruction::Unreachable:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001193 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1194 printSimpleInstruction("newobj",
1195 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001196 printSimpleInstruction("throw");
1197 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001198 case Instruction::VAArg:
1199 printVAArgInstruction(cast<VAArgInst>(Inst));
1200 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001201 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001202 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001203 llvm_unreachable("Unsupported instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001204 }
1205}
1206
1207
1208void MSILWriter::printLoop(const Loop* L) {
1209 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1210 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1211 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1212 BasicBlock* BB = blocks[I];
1213 Loop* BBLoop = LInfo->getLoopFor(BB);
1214 if (BBLoop == L)
1215 printBasicBlock(BB);
1216 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1217 printLoop(BBLoop);
1218 }
1219 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1220}
1221
1222
1223void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1224 Out << getLabelName(BB) << ":\n";
1225 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1226 const Instruction* Inst = I;
1227 // Comment llvm original instruction
Owen Andersoncb371882008-08-21 00:14:44 +00001228 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001229 // Do not handle PHI instruction in current block
1230 if (Inst->getOpcode()==Instruction::PHI) continue;
1231 // Print instruction
1232 printInstruction(Inst);
1233 // Save result
Owen Anderson1d0be152009-08-13 21:58:54 +00001234 if (Inst->getType()!=Type::getVoidTy(BB->getContext())) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001235 // Do not save value after invoke, it done in "try" block
1236 if (Inst->getOpcode()==Instruction::Invoke) continue;
1237 printValueSave(Inst);
1238 }
1239 }
1240}
1241
1242
1243void MSILWriter::printLocalVariables(const Function& F) {
1244 std::string Name;
1245 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001246 std::set<const Value*> Printed;
1247 const Value* VaList = NULL;
1248 unsigned StackDepth = 8;
1249 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001250 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001251 if (I->getOpcode()==Instruction::Call ||
1252 I->getOpcode()==Instruction::Invoke) {
1253 // Test stack depth.
1254 if (StackDepth<I->getNumOperands())
1255 StackDepth = I->getNumOperands();
1256 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001257 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1258 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001259 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001260 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001261 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001262 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00001263 } else if (I->getType()!=Type::getVoidTy(F.getContext())) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001264 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001265 Ty = I->getType();
1266 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001267 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1268 }
1269 // Test on 'va_list' variable
1270 bool isVaList = false;
1271 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1272 // "va_list" as "va_arg" instruction operand.
1273 isVaList = true;
1274 VaList = VaInst->getOperand(0);
1275 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1276 // "va_list" as intrinsic function operand.
1277 switch (Inst->getIntrinsicID()) {
1278 case Intrinsic::vastart:
1279 case Intrinsic::vaend:
1280 case Intrinsic::vacopy:
1281 isVaList = true;
1282 VaList = Inst->getOperand(1);
1283 break;
1284 default:
1285 isVaList = false;
1286 }
1287 }
1288 // Print "va_list" variable.
1289 if (isVaList && Printed.insert(VaList).second) {
1290 Name = getValueName(VaList);
1291 Name.insert(Name.length()-1,"$valist");
1292 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1293 << Name << ")\n";
1294 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001295 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001296 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001297}
1298
1299
1300void MSILWriter::printFunctionBody(const Function& F) {
1301 // Print body
1302 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1303 if (Loop *L = LInfo->getLoopFor(I)) {
1304 if (L->getHeader()==I && L->getParentLoop()==0)
1305 printLoop(L);
1306 } else {
1307 printBasicBlock(I);
1308 }
1309 }
1310}
1311
1312
1313void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1314 const Value *left = 0, *right = 0;
1315 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1316 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1317 // Print instruction
1318 switch (CE->getOpcode()) {
1319 case Instruction::Trunc:
1320 case Instruction::ZExt:
1321 case Instruction::SExt:
1322 case Instruction::FPTrunc:
1323 case Instruction::FPExt:
1324 case Instruction::UIToFP:
1325 case Instruction::SIToFP:
1326 case Instruction::FPToUI:
1327 case Instruction::FPToSI:
1328 case Instruction::PtrToInt:
1329 case Instruction::IntToPtr:
1330 case Instruction::BitCast:
1331 printCastInstruction(CE->getOpcode(),left,CE->getType());
1332 break;
1333 case Instruction::GetElementPtr:
1334 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1335 break;
1336 case Instruction::ICmp:
1337 printICmpInstruction(CE->getPredicate(),left,right);
1338 break;
1339 case Instruction::FCmp:
1340 printFCmpInstruction(CE->getPredicate(),left,right);
1341 break;
1342 case Instruction::Select:
1343 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1344 break;
1345 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001346 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001347 printBinaryInstruction("add",left,right);
1348 break;
1349 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001350 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001351 printBinaryInstruction("sub",left,right);
1352 break;
1353 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001354 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001355 printBinaryInstruction("mul",left,right);
1356 break;
1357 case Instruction::UDiv:
1358 printBinaryInstruction("div.un",left,right);
1359 break;
1360 case Instruction::SDiv:
1361 case Instruction::FDiv:
1362 printBinaryInstruction("div",left,right);
1363 break;
1364 case Instruction::URem:
1365 printBinaryInstruction("rem.un",left,right);
1366 break;
1367 case Instruction::SRem:
1368 case Instruction::FRem:
1369 printBinaryInstruction("rem",left,right);
1370 break;
1371 case Instruction::And:
1372 printBinaryInstruction("and",left,right);
1373 break;
1374 case Instruction::Or:
1375 printBinaryInstruction("or",left,right);
1376 break;
1377 case Instruction::Xor:
1378 printBinaryInstruction("xor",left,right);
1379 break;
1380 case Instruction::Shl:
1381 printBinaryInstruction("shl",left,right);
1382 break;
1383 case Instruction::LShr:
1384 printBinaryInstruction("shr.un",left,right);
1385 break;
1386 case Instruction::AShr:
1387 printBinaryInstruction("shr",left,right);
1388 break;
1389 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001390 errs() << "Expression = " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001391 llvm_unreachable("Invalid constant expression");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001392 }
1393}
1394
1395
1396void MSILWriter::printStaticInitializerList() {
1397 // List of global variables with uninitialized fields.
1398 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1399 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1400 ++VarI) {
1401 const std::vector<StaticInitializer>& InitList = VarI->second;
1402 if (InitList.empty()) continue;
1403 // For each uninitialized field.
1404 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1405 E = InitList.end(); I!=E; ++I) {
1406 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001407 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1408 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001409 // Load variable address
1410 printValueLoad(VarI->first);
1411 // Add offset
1412 if (I->offset!=0) {
1413 printPtrLoad(I->offset);
1414 printSimpleInstruction("add");
1415 }
1416 // Load value
1417 printConstantExpr(CE);
1418 // Save result at offset
1419 std::string postfix = getTypePostfix(CE->getType(),true);
1420 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1421 postfix = "stind."+postfix;
1422 printSimpleInstruction(postfix.c_str());
1423 } else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001424 errs() << "Constant = " << *I->constant << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001425 llvm_unreachable("Invalid static initializer");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001426 }
1427 }
1428 }
1429}
1430
1431
1432void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001433 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001434 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001435 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001436 if (F.isVarArg()) Out << "vararg ";
1437 Out << getTypeName(F.getReturnType(),isSigned) <<
1438 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1439 // Arguments
1440 Out << "\t(";
1441 unsigned ArgIdx = 1;
1442 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1443 ++I, ++ArgIdx) {
Devang Patel05988662008-09-25 21:00:45 +00001444 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001445 if (I!=F.arg_begin()) Out << ", ";
1446 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1447 }
1448 Out << ") cil managed\n";
1449 // Body
1450 Out << "{\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001451 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001452 printFunctionBody(F);
1453 Out << "}\n";
1454}
1455
1456
1457void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1458 std::string Name;
1459 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001460 for (std::set<const Type*>::const_iterator
1461 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1462 const Type* Ty = *UI;
Duncan Sands1df98592010-02-16 11:11:14 +00001463 if (Ty->isArrayTy() || Ty->isVectorTy() || Ty->isStructTy())
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001464 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001465 // Type with no need to declare.
1466 else continue;
1467 // Print not duplicated type
1468 if (Printed.insert(Ty).second) {
1469 Out << ".class value explicit ansi sealed '" << Name << "'";
Duncan Sands777d2302009-05-09 07:06:46 +00001470 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001471 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001472 }
1473 }
1474}
1475
1476
1477unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1478 unsigned int N = Ty->getPrimitiveSizeInBits();
1479 assert(N!=0 && "Invalid type in getBitWidth()");
1480 switch (N) {
1481 case 1:
1482 case 8:
1483 case 16:
1484 case 32:
1485 case 64:
1486 return N;
1487 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001488 errs() << "Bits = " << N << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001489 llvm_unreachable("Unsupported integer width");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001490 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001491 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001492}
1493
1494
1495void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1496 uint64_t TySize = 0;
1497 const Type* Ty = C->getType();
1498 // Print zero initialized constant.
1499 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
Duncan Sands777d2302009-05-09 07:06:46 +00001500 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001501 Offset += TySize;
1502 Out << "int8 (0) [" << TySize << "]";
1503 return;
1504 }
1505 // Print constant initializer
1506 switch (Ty->getTypeID()) {
1507 case Type::IntegerTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001508 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001509 const ConstantInt* Int = cast<ConstantInt>(C);
1510 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1511 break;
1512 }
1513 case Type::FloatTyID:
1514 case Type::DoubleTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001515 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001516 const ConstantFP* FP = cast<ConstantFP>(C);
1517 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001518 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001519 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001520 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001521 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001522 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001523 break;
1524 }
1525 case Type::ArrayTyID:
1526 case Type::VectorTyID:
1527 case Type::StructTyID:
1528 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1529 if (I!=0) Out << ",\n";
Chris Lattner0eeb9132009-10-28 05:14:34 +00001530 printStaticConstant(cast<Constant>(C->getOperand(I)), Offset);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001531 }
1532 break;
1533 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +00001534 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001535 // Initialize with global variable address
1536 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1537 std::string name = getValueName(G);
1538 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1539 } else {
1540 // Dynamic initialization
1541 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1542 InitListPtr->push_back(StaticInitializer(C,Offset));
1543 // Null pointer initialization
1544 if (TySize==4) Out << "int32 (0)";
1545 else if (TySize==8) Out << "int64 (0)";
Torok Edwinc23197a2009-07-14 16:55:14 +00001546 else llvm_unreachable("Invalid pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001547 }
1548 break;
1549 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001550 errs() << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001551 llvm_unreachable("Invalid type in printStaticConstant()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001552 }
1553 // Increase offset.
1554 Offset += TySize;
1555}
1556
1557
1558void MSILWriter::printStaticInitializer(const Constant* C,
1559 const std::string& Name) {
1560 switch (C->getType()->getTypeID()) {
1561 case Type::IntegerTyID:
1562 case Type::FloatTyID:
1563 case Type::DoubleTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001564 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001565 break;
1566 case Type::ArrayTyID:
1567 case Type::VectorTyID:
1568 case Type::StructTyID:
1569 case Type::PointerTyID:
1570 Out << getTypeName(C->getType());
1571 break;
1572 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001573 errs() << "Type = " << *C << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001574 llvm_unreachable("Invalid constant type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001575 }
1576 // Print initializer
1577 std::string label = Name;
1578 label.insert(label.length()-1,"$data");
1579 Out << Name << " at " << label << '\n';
1580 Out << ".data " << label << " = {\n";
1581 uint64_t offset = 0;
1582 printStaticConstant(C,offset);
1583 Out << "\n}\n\n";
1584}
1585
1586
1587void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1588 const Constant* C = G->getInitializer();
1589 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1590 InitListPtr = 0;
1591 else
1592 InitListPtr = &StaticInitList[G];
1593 printStaticInitializer(C,getValueName(G));
1594}
1595
1596
1597void MSILWriter::printGlobalVariables() {
1598 if (ModulePtr->global_empty()) return;
1599 Module::global_iterator I,E;
1600 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1601 // Variable definition
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001602 Out << ".field static " << (I->isDeclaration() ? "public " :
1603 "private ");
1604 if (I->isDeclaration()) {
1605 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1606 } else
1607 printVariableDefinition(&*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001608 }
1609}
1610
1611
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001612const char* MSILWriter::getLibraryName(const Function* F) {
Daniel Dunbarbda96532009-07-21 08:57:31 +00001613 return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001614}
1615
1616
1617const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
Chris Lattner27891032010-01-16 02:15:38 +00001618 return getLibraryForSymbol(GV->getName(), false, CallingConv::C);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001619}
1620
1621
Daniel Dunbarbda96532009-07-21 08:57:31 +00001622const char* MSILWriter::getLibraryForSymbol(const StringRef &Name,
1623 bool isFunction,
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001624 CallingConv::ID CallingConv) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001625 // TODO: Read *.def file with function and libraries definitions.
1626 return "MSVCRT.DLL";
1627}
1628
1629
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001630void MSILWriter::printExternals() {
1631 Module::const_iterator I,E;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001632 // Functions.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001633 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1634 // Skip intrisics
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001635 if (I->isIntrinsic()) continue;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001636 if (I->isDeclaration()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001637 const Function* F = I;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001638 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001639 std::string Sig =
1640 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1641 Out << ".method static hidebysig pinvokeimpl(\""
1642 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001643 }
1644 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001645 // External variables and static initialization.
1646 Out <<
1647 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1648 " native int LoadLibrary(string) preservesig {}\n"
1649 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1650 " native int GetProcAddress(native int, string) preservesig {}\n";
1651 Out <<
1652 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1653 " managed cil\n{\n"
1654 "\tldarg\tlib\n"
1655 "\tcall\tnative int LoadLibrary(string)\n"
1656 "\tldarg\tsym\n"
1657 "\tcall\tnative int GetProcAddress(native int,string)\n"
1658 "\tdup\n"
1659 "\tbrtrue\tL_01\n"
1660 "\tldstr\t\"Can no import variable\"\n"
1661 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1662 "\tthrow\n"
1663 "L_01:\n"
1664 "\tret\n"
1665 "}\n\n"
1666 ".method static private void $MSIL_Init() managed cil\n{\n";
1667 printStaticInitializerList();
1668 // Foreach global variable.
1669 for (Module::global_iterator I = ModulePtr->global_begin(),
1670 E = ModulePtr->global_end(); I!=E; ++I) {
1671 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1672 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001673 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1674 printSimpleInstruction("ldsflda",Tmp.c_str());
1675 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
Chris Lattner27891032010-01-16 02:15:38 +00001676 Out << "\tldstr\t\"" << I->getName() << "\"\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001677 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1678 printIndirectSave(I->getType());
1679 }
1680 printSimpleInstruction("ret");
1681 Out << "}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001682}
1683
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001684
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001685//===----------------------------------------------------------------------===//
Bill Wendling85db3a92008-02-26 10:57:23 +00001686// External Interface declaration
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001687//===----------------------------------------------------------------------===//
1688
David Greene71847812009-07-14 20:18:05 +00001689bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1690 formatted_raw_ostream &o,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001691 CodeGenFileType FileType,
Dan Gohman8772f502010-02-28 00:41:59 +00001692 CodeGenOpt::Level OptLevel,
1693 bool DisableVerify)
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001694{
Chris Lattner211edae2010-02-02 21:06:45 +00001695 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001696 MSILWriter* Writer = new MSILWriter(o);
Gordon Henriksence224772008-01-07 01:30:38 +00001697 PM.add(createGCLoweringPass());
Eric Christopher5e639902009-12-18 02:12:53 +00001698 // FIXME: Handle switch through native IL instruction "switch"
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001699 PM.add(createLowerSwitchPass());
1700 PM.add(createCFGSimplificationPass());
1701 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1702 PM.add(Writer);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001703 PM.add(createGCInfoDeleter());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001704 return false;
1705}