blob: 3de173cc26ceb17ccbf9970a4764e8491318c0e5 [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
Dan Gohman99dca4f2010-05-11 19:57:55 +000037 virtual bool addPassesToEmitFile(PassManagerBase &PM,
38 formatted_raw_ostream &Out,
39 CodeGenFileType FileType,
40 CodeGenOpt::Level OptLevel,
41 bool DisableVerify);
Anton Korobeynikov099883f2007-03-21 21:38:25 +000042
Daniel Dunbard1a919e2009-08-03 17:40:25 +000043 virtual const TargetData *getTargetData() const { return 0; }
Anton Korobeynikov099883f2007-03-21 21:38:25 +000044 };
45}
46
Daniel Dunbar0c795d62009-07-25 06:49:55 +000047extern "C" void LLVMInitializeMSILTarget() {
48 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000049 RegisterTargetMachine<MSILTarget> X(TheMSILTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000050}
Douglas Gregor1555a232009-06-16 20:12:29 +000051
Anton Korobeynikov099883f2007-03-21 21:38:25 +000052bool MSILModule::runOnModule(Module &M) {
53 ModulePtr = &M;
54 TD = &getAnalysis<TargetData>();
55 bool Changed = false;
56 // Find named types.
57 TypeSymbolTable& Table = M.getTypeSymbolTable();
58 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
59 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
Duncan Sands47c51882010-02-16 14:50:09 +000060 if (!I->second->isStructTy() && !I->second->isOpaqueTy())
Anton Korobeynikov099883f2007-03-21 21:38:25 +000061 Table.remove(I++);
62 else {
63 std::set<const Type *>::iterator T = Types.find(I->second);
64 if (T==Types.end())
65 Table.remove(I++);
66 else {
67 Types.erase(T);
68 ++I;
69 }
70 }
71 }
72 // Find unnamed types.
73 unsigned RenameCounter = 0;
74 for (std::set<const Type *>::const_iterator I = Types.begin(),
75 E = Types.end(); I!=E; ++I)
76 if (const StructType *STy = dyn_cast<StructType>(*I)) {
77 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
78 ++RenameCounter;
79 Changed = true;
80 }
81 // Pointer for FunctionPass.
82 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
83 return Changed;
84}
85
Devang Patel19974732007-05-03 01:11:54 +000086char MSILModule::ID = 0;
87char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000088
89bool MSILWriter::runOnFunction(Function &F) {
90 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +000091
92 // Do not codegen any 'available_externally' functions at all, they have
93 // definitions outside the translation unit.
94 if (F.hasAvailableExternallyLinkage())
95 return false;
96
Anton Korobeynikov099883f2007-03-21 21:38:25 +000097 LInfo = &getAnalysis<LoopInfo>();
98 printFunction(F);
99 return false;
100}
101
102
103bool MSILWriter::doInitialization(Module &M) {
104 ModulePtr = &M;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000105 Out << ".assembly extern mscorlib {}\n";
106 Out << ".assembly MSIL {}\n\n";
107 Out << "// External\n";
108 printExternals();
109 Out << "// Declarations\n";
110 printDeclarations(M.getTypeSymbolTable());
111 Out << "// Definitions\n";
112 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000113 Out << "// Startup code\n";
114 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000115 return false;
116}
117
118
119bool MSILWriter::doFinalization(Module &M) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000120 return false;
121}
122
123
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000124void MSILWriter::printModuleStartup() {
125 Out <<
126 ".method static public int32 $MSIL_Startup() {\n"
127 "\t.entrypoint\n"
128 "\t.locals (native int i)\n"
129 "\t.locals (native int argc)\n"
130 "\t.locals (native int ptr)\n"
131 "\t.locals (void* argv)\n"
132 "\t.locals (string[] args)\n"
133 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
134 "\tdup\n"
135 "\tstloc\targs\n"
136 "\tldlen\n"
137 "\tconv.i4\n"
138 "\tdup\n"
139 "\tstloc\targc\n";
140 printPtrLoad(TD->getPointerSize());
141 Out <<
142 "\tmul\n"
143 "\tlocalloc\n"
144 "\tstloc\targv\n"
145 "\tldc.i4.0\n"
146 "\tstloc\ti\n"
147 "L_01:\n"
148 "\tldloc\ti\n"
149 "\tldloc\targc\n"
150 "\tceq\n"
151 "\tbrtrue\tL_02\n"
152 "\tldloc\targs\n"
153 "\tldloc\ti\n"
154 "\tldelem.ref\n"
155 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
156 "StringToHGlobalAnsi(string)\n"
157 "\tstloc\tptr\n"
158 "\tldloc\targv\n"
159 "\tldloc\ti\n";
160 printPtrLoad(TD->getPointerSize());
161 Out <<
162 "\tmul\n"
163 "\tadd\n"
164 "\tldloc\tptr\n"
165 "\tstind.i\n"
166 "\tldloc\ti\n"
167 "\tldc.i4.1\n"
168 "\tadd\n"
169 "\tstloc\ti\n"
170 "\tbr\tL_01\n"
171 "L_02:\n"
172 "\tcall void $MSIL_Init()\n";
173
174 // Call user 'main' function.
175 const Function* F = ModulePtr->getFunction("main");
176 if (!F || F->isDeclaration()) {
177 Out << "\tldc.i4.0\n\tret\n}\n";
178 return;
179 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000180 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000181 std::string Args("");
182 Function::const_arg_iterator Arg1,Arg2;
183
184 switch (F->arg_size()) {
185 case 0:
186 BadSig = false;
187 break;
188 case 1:
189 Arg1 = F->arg_begin();
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000190 if (Arg1->getType()->isIntegerTy()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000191 Out << "\tldloc\targc\n";
192 Args = getTypeName(Arg1->getType());
193 BadSig = false;
194 }
195 break;
196 case 2:
197 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000198 if (Arg1->getType()->isIntegerTy() &&
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000199 Arg2->getType()->getTypeID() == Type::PointerTyID) {
200 Out << "\tldloc\targc\n\tldloc\targv\n";
201 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
202 BadSig = false;
203 }
204 break;
205 default:
206 BadSig = true;
207 }
208
209 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000210 if (BadSig || (!F->getReturnType()->isIntegerTy() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000211 Out << "\tldc.i4.0\n";
212 } else {
213 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
214 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
215 if (RetVoid)
216 Out << "\tldc.i4.0\n";
217 else
218 Out << "\tconv.i4\n";
219 }
220 Out << "\tret\n}\n";
221}
222
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000223bool MSILWriter::isZeroValue(const Value* V) {
224 if (const Constant *C = dyn_cast<Constant>(V))
225 return C->isNullValue();
226 return false;
227}
228
229
230std::string MSILWriter::getValueName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000231 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000232 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattner27891032010-01-16 02:15:38 +0000233 Name = GV->getName();
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000234 else {
235 unsigned &No = AnonValueNumbers[V];
236 if (No == 0) No = ++NextAnonValueNumber;
237 Name = "tmp" + utostr(No);
238 }
239
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000240 // Name into the quotes allow control and space characters.
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000241 return "'"+Name+"'";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000242}
243
244
245std::string MSILWriter::getLabelName(const std::string& Name) {
246 if (Name.find('.')!=std::string::npos) {
247 std::string Tmp(Name);
248 // Replace unaccepable characters in the label name.
249 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
250 if (*I=='.') *I = '@';
251 return Tmp;
252 }
253 return Name;
254}
255
256
257std::string MSILWriter::getLabelName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000258 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000259 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattner27891032010-01-16 02:15:38 +0000260 Name = GV->getName();
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000261 else {
262 unsigned &No = AnonValueNumbers[V];
263 if (No == 0) No = ++NextAnonValueNumber;
264 Name = "tmp" + utostr(No);
265 }
266
267 return getLabelName(Name);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000268}
269
270
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000271std::string MSILWriter::getConvModopt(CallingConv::ID CallingConvID) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000272 switch (CallingConvID) {
273 case CallingConv::C:
274 case CallingConv::Cold:
275 case CallingConv::Fast:
276 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
277 case CallingConv::X86_FastCall:
278 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
279 case CallingConv::X86_StdCall:
280 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
Anton Korobeynikovded05e32010-05-16 09:08:45 +0000281 case CallingConv::X86_ThisCall:
282 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvThiscall) ";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000283 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000284 errs() << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000285 llvm_unreachable("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000286 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000287 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000288}
289
290
291std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
292 std::string Tmp = "";
293 const Type* ElemTy = Ty;
294 assert(Ty->getTypeID()==TyID && "Invalid type passed");
295 // Walk trought array element types.
296 for (;;) {
297 // Multidimensional array.
298 if (ElemTy->getTypeID()==TyID) {
299 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
300 Tmp += utostr(ATy->getNumElements());
301 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
302 Tmp += utostr(VTy->getNumElements());
303 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
304 }
305 // Base element type found.
306 if (ElemTy->getTypeID()!=TyID) break;
307 Tmp += ",";
308 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000309 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000310}
311
312
313std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
314 unsigned NumBits = 0;
315 switch (Ty->getTypeID()) {
316 case Type::VoidTyID:
317 return "void ";
318 case Type::IntegerTyID:
319 NumBits = getBitWidth(Ty);
320 if(NumBits==1)
321 return "bool ";
322 if (!isSigned)
323 return "unsigned int"+utostr(NumBits)+" ";
324 return "int"+utostr(NumBits)+" ";
325 case Type::FloatTyID:
326 return "float32 ";
327 case Type::DoubleTyID:
328 return "float64 ";
329 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000330 errs() << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000331 llvm_unreachable("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000332 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000333 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000334}
335
336
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000337std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
338 bool isNested) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000339 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000340 return getPrimitiveTypeName(Ty,isSigned);
341 // FIXME: "OpaqueType" support
342 switch (Ty->getTypeID()) {
343 case Type::PointerTyID:
344 return "void* ";
345 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000346 if (isNested)
347 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000348 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
349 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000350 if (isNested)
351 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000352 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
353 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000354 if (isNested)
355 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000356 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
357 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000358 errs() << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000359 llvm_unreachable("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000360 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000361 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000362}
363
364
365MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
366 // Function argument
367 if (isa<Argument>(V))
368 return ArgumentVT;
369 // Function
370 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000371 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000372 // Variable
373 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000374 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000375 // Constant
376 else if (isa<Constant>(V))
377 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
378 // Local variable
379 return LocalVT;
380}
381
382
383std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
384 bool isSigned) {
385 unsigned NumBits = 0;
386 switch (Ty->getTypeID()) {
387 // Integer constant, expanding for stack operations.
388 case Type::IntegerTyID:
389 NumBits = getBitWidth(Ty);
390 // Expand integer value to "int32" or "int64".
391 if (Expand) return (NumBits<=32 ? "i4" : "i8");
392 if (NumBits==1) return "i1";
393 return (isSigned ? "i" : "u")+utostr(NumBits/8);
394 // Float constant.
395 case Type::FloatTyID:
396 return "r4";
397 case Type::DoubleTyID:
398 return "r8";
399 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000400 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000401 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000402 errs() << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000403 llvm_unreachable("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000404 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000405 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000406}
407
408
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000409void MSILWriter::printConvToPtr() {
410 switch (ModulePtr->getPointerSize()) {
411 case Module::Pointer32:
412 printSimpleInstruction("conv.u4");
413 break;
414 case Module::Pointer64:
415 printSimpleInstruction("conv.u8");
416 break;
417 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000418 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000419 }
420}
421
422
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000423void MSILWriter::printPtrLoad(uint64_t N) {
424 switch (ModulePtr->getPointerSize()) {
425 case Module::Pointer32:
426 printSimpleInstruction("ldc.i4",utostr(N).c_str());
427 // FIXME: Need overflow test?
Benjamin Kramer34247a02010-03-29 21:13:41 +0000428 if (!isUInt<32>(N)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000429 errs() << "Value = " << utostr(N) << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000430 llvm_unreachable("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000431 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000432 break;
433 case Module::Pointer64:
434 printSimpleInstruction("ldc.i8",utostr(N).c_str());
435 break;
436 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000437 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000438 }
439}
440
441
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000442void MSILWriter::printValuePtrLoad(const Value* V) {
443 printValueLoad(V);
444 printConvToPtr();
445}
446
447
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000448void MSILWriter::printConstLoad(const Constant* C) {
449 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
450 // Integer constant
451 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
452 if (CInt->isMinValue(true))
453 Out << CInt->getSExtValue();
454 else
455 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000456 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000457 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000458 uint64_t X;
459 unsigned Size;
460 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000461 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000462 Size = 4;
463 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000464 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000465 Size = 8;
466 }
467 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
468 } else if (isa<UndefValue>(C)) {
469 // Undefined constant value = NULL.
470 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000471 } else {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000472 errs() << "Constant = " << *C << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000473 llvm_unreachable("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000474 }
475 Out << '\n';
476}
477
478
479void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000480 MSILWriter::ValueType Location = getValueLocation(V);
481 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000482 // Global variable or function address.
483 case GlobalVT:
484 case InternalVT:
485 if (const Function* F = dyn_cast<Function>(V)) {
486 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
487 printSimpleInstruction("ldftn",
488 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
489 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000490 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000491 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000492 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
493 Tmp = "void* "+getValueName(V);
494 printSimpleInstruction("ldsfld",Tmp.c_str());
495 } else {
496 Tmp = getTypeName(ElemTy)+getValueName(V);
497 printSimpleInstruction("ldsflda",Tmp.c_str());
498 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000499 }
500 break;
501 // Function argument.
502 case ArgumentVT:
503 printSimpleInstruction("ldarg",getValueName(V).c_str());
504 break;
505 // Local function variable.
506 case LocalVT:
507 printSimpleInstruction("ldloc",getValueName(V).c_str());
508 break;
509 // Constant value.
510 case ConstVT:
511 if (isa<ConstantPointerNull>(V))
512 printPtrLoad(0);
513 else
514 printConstLoad(cast<Constant>(V));
515 break;
516 // Constant expression.
517 case ConstExprVT:
518 printConstantExpr(cast<ConstantExpr>(V));
519 break;
520 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000521 errs() << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000522 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000523 }
524}
525
526
527void MSILWriter::printValueSave(const Value* V) {
528 switch (getValueLocation(V)) {
529 case ArgumentVT:
530 printSimpleInstruction("starg",getValueName(V).c_str());
531 break;
532 case LocalVT:
533 printSimpleInstruction("stloc",getValueName(V).c_str());
534 break;
535 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000536 errs() << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000537 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000538 }
539}
540
541
542void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
543 const Value* Right) {
544 printValueLoad(Left);
545 printValueLoad(Right);
546 Out << '\t' << Name << '\n';
547}
548
549
550void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
551 if(Operand)
552 Out << '\t' << Inst << '\t' << Operand << '\n';
553 else
554 Out << '\t' << Inst << '\n';
555}
556
557
558void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
Bill Wendling3ef10852009-12-28 01:42:12 +0000559 for (BasicBlock::const_iterator I = Dst->begin(); isa<PHINode>(I); ++I) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000560 const PHINode* Phi = cast<PHINode>(I);
561 const Value* Val = Phi->getIncomingValueForBlock(Src);
562 if (isa<UndefValue>(Val)) continue;
563 printValueLoad(Val);
564 printValueSave(Phi);
565 }
566}
567
568
569void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
570 const BasicBlock* TrueBB,
571 const BasicBlock* FalseBB) {
572 if (TrueBB==FalseBB) {
573 // "TrueBB" and "FalseBB" destination equals
574 printPHICopy(CurrBB,TrueBB);
575 printSimpleInstruction("pop");
576 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
577 } else if (FalseBB==NULL) {
578 // If "FalseBB" not used the jump have condition
579 printPHICopy(CurrBB,TrueBB);
580 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
581 } else if (TrueBB==NULL) {
582 // If "TrueBB" not used the jump is unconditional
583 printPHICopy(CurrBB,FalseBB);
584 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
585 } else {
586 // Copy PHI instructions for each block
587 std::string TmpLabel;
588 // Print PHI instructions for "TrueBB"
589 if (isa<PHINode>(TrueBB->begin())) {
590 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
591 printSimpleInstruction("brtrue",TmpLabel.c_str());
592 } else {
593 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
594 }
595 // Print PHI instructions for "FalseBB"
596 if (isa<PHINode>(FalseBB->begin())) {
597 printPHICopy(CurrBB,FalseBB);
598 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
599 } else {
600 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
601 }
602 if (isa<PHINode>(TrueBB->begin())) {
603 // Handle "TrueBB" PHI Copy
604 Out << TmpLabel << ":\n";
605 printPHICopy(CurrBB,TrueBB);
606 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
607 }
608 }
609}
610
611
612void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
613 if (Inst->isUnconditional()) {
614 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
615 } else {
616 printValueLoad(Inst->getCondition());
617 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
618 Inst->getSuccessor(1));
619 }
620}
621
622
623void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
624 const Value* VFalse) {
625 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
626 printValueLoad(VTrue);
627 printValueLoad(Cond);
628 printSimpleInstruction("brtrue",TmpLabel.c_str());
629 printSimpleInstruction("pop");
630 printValueLoad(VFalse);
631 Out << TmpLabel << ":\n";
632}
633
634
635void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000636 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000637 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000638 if (const PointerType* P = dyn_cast<PointerType>(Ty))
639 Ty = P->getElementType();
640 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000641 printSimpleInstruction(Tmp.c_str());
642}
643
644
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000645void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000646 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000647 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000648 printIndirectSave(Val->getType());
649}
650
651
652void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000653 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000654 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000655 if (*postfix.begin()=='u') *postfix.begin() = 'i';
656 postfix = "stind."+postfix;
657 printSimpleInstruction(postfix.c_str());
658}
659
660
661void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000662 const Type* Ty, const Type* SrcTy) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000663 std::string Tmp("");
664 printValueLoad(V);
665 switch (Op) {
666 // Signed
667 case Instruction::SExt:
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000668 // If sign extending int, convert first from unsigned to signed
669 // with the same bit size - because otherwise we will loose the sign.
670 if (SrcTy) {
671 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
672 printSimpleInstruction(Tmp.c_str());
673 }
Bill Wendling5f544502009-07-14 18:30:04 +0000674 // FALLTHROUGH
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000675 case Instruction::SIToFP:
676 case Instruction::FPToSI:
677 Tmp = "conv."+getTypePostfix(Ty,false,true);
678 printSimpleInstruction(Tmp.c_str());
679 break;
680 // Unsigned
681 case Instruction::FPTrunc:
682 case Instruction::FPExt:
683 case Instruction::UIToFP:
684 case Instruction::Trunc:
685 case Instruction::ZExt:
686 case Instruction::FPToUI:
687 case Instruction::PtrToInt:
688 case Instruction::IntToPtr:
689 Tmp = "conv."+getTypePostfix(Ty,false);
690 printSimpleInstruction(Tmp.c_str());
691 break;
692 // Do nothing
693 case Instruction::BitCast:
694 // FIXME: meaning that ld*/st* instruction do not change data format.
695 break;
696 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000697 errs() << "Opcode = " << Op << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000698 llvm_unreachable("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000699 }
700}
701
702
703void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
704 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000705 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000706 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000707 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000708 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000709 for (; I!=E; ++I){
710 Size = 0;
711 const Value* IndexValue = I.getOperand();
712 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
713 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
714 // Offset is the sum of all previous structure fields.
715 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000716 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000717 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000718 printSimpleInstruction("add");
719 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000720 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000721 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000722 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000723 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000724 }
725 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000726 if (!isZeroValue(IndexValue)) {
727 // Constant optimization.
728 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
729 if (C->getValue().isNegative()) {
730 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
731 printSimpleInstruction("sub");
732 continue;
733 } else
734 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000735 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000736 printPtrLoad(Size);
737 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000738 printSimpleInstruction("mul");
739 }
740 printSimpleInstruction("add");
741 }
742 }
743}
744
745
746std::string MSILWriter::getCallSignature(const FunctionType* Ty,
747 const Instruction* Inst,
748 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000749 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000750 if (Ty->isVarArg()) Tmp += "vararg ";
751 // Name and return type.
752 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
753 // Function argument type list.
754 unsigned NumParams = Ty->getNumParams();
755 for (unsigned I = 0; I!=NumParams; ++I) {
756 if (I!=0) Tmp += ",";
757 Tmp += getTypeName(Ty->getParamType(I));
758 }
759 // CLR needs to know the exact amount of parameters received by vararg
760 // function, because caller cleans the stack.
761 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000762 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000763 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
764 // Print variable argument types.
765 unsigned NumOperands = Inst->getNumOperands()-Org;
766 if (NumParams<NumOperands) {
767 if (NumParams!=0) Tmp += ", ";
768 Tmp += "... , ";
769 for (unsigned J = NumParams; J!=NumOperands; ++J) {
770 if (J!=NumParams) Tmp += ", ";
771 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
772 }
773 }
774 }
775 return Tmp+")";
776}
777
778
779void MSILWriter::printFunctionCall(const Value* FnVal,
780 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000781 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000782 std::string Name = "";
783 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
784 Name = getConvModopt(Call->getCallingConv());
785 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
786 Name = getConvModopt(Invoke->getCallingConv());
787 else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000788 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000789 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000790 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000791 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000792 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000793 Name += getValueName(F);
794 printSimpleInstruction("call",
795 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
796 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000797 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000798 const PointerType* PTy = cast<PointerType>(FnVal->getType());
799 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000800 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000801 printValueLoad(FnVal);
802 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
803 }
804}
805
806
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000807void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
808 std::string Name;
809 switch (Inst->getIntrinsicID()) {
810 case Intrinsic::vastart:
811 Name = getValueName(Inst->getOperand(1));
812 Name.insert(Name.length()-1,"$valist");
813 // Obtain the argument handle.
814 printSimpleInstruction("ldloca",Name.c_str());
815 printSimpleInstruction("arglist");
816 printSimpleInstruction("call",
817 "instance void [mscorlib]System.ArgIterator::.ctor"
818 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
819 // Save as pointer type "void*"
820 printValueLoad(Inst->getOperand(1));
821 printSimpleInstruction("ldloca",Name.c_str());
Owen Anderson1d0be152009-08-13 21:58:54 +0000822 printIndirectSave(PointerType::getUnqual(
823 IntegerType::get(Inst->getContext(), 8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000824 break;
825 case Intrinsic::vaend:
826 // Close argument list handle.
827 printIndirectLoad(Inst->getOperand(1));
828 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
829 break;
830 case Intrinsic::vacopy:
831 // Copy "ArgIterator" valuetype.
832 printIndirectLoad(Inst->getOperand(1));
833 printIndirectLoad(Inst->getOperand(2));
834 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
835 break;
836 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000837 errs() << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000838 llvm_unreachable("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000839 }
840}
841
842
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000843void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000844 if (isa<IntrinsicInst>(Inst)) {
845 // Handle intrinsic function.
846 printIntrinsicCall(cast<IntrinsicInst>(Inst));
847 } else {
848 // Load arguments to stack and call function.
849 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
850 printValueLoad(Inst->getOperand(I));
851 printFunctionCall(Inst->getOperand(0),Inst);
852 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000853}
854
855
856void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
857 const Value* Right) {
858 switch (Predicate) {
859 case ICmpInst::ICMP_EQ:
860 printBinaryInstruction("ceq",Left,Right);
861 break;
862 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000863 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000864 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000865 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000866 printSimpleInstruction("not");
867 break;
868 case ICmpInst::ICMP_ULE:
869 case ICmpInst::ICMP_SLE:
870 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
871 printBinaryInstruction("ceq",Left,Right);
872 if (Predicate==ICmpInst::ICMP_ULE)
873 printBinaryInstruction("clt.un",Left,Right);
874 else
875 printBinaryInstruction("clt",Left,Right);
876 printSimpleInstruction("or");
877 break;
878 case ICmpInst::ICMP_UGE:
879 case ICmpInst::ICMP_SGE:
880 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
881 printBinaryInstruction("ceq",Left,Right);
882 if (Predicate==ICmpInst::ICMP_UGE)
883 printBinaryInstruction("cgt.un",Left,Right);
884 else
885 printBinaryInstruction("cgt",Left,Right);
886 printSimpleInstruction("or");
887 break;
888 case ICmpInst::ICMP_ULT:
889 printBinaryInstruction("clt.un",Left,Right);
890 break;
891 case ICmpInst::ICMP_SLT:
892 printBinaryInstruction("clt",Left,Right);
893 break;
894 case ICmpInst::ICMP_UGT:
895 printBinaryInstruction("cgt.un",Left,Right);
Anton Korobeynikove9fd67e2009-07-14 09:52:47 +0000896 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000897 case ICmpInst::ICMP_SGT:
898 printBinaryInstruction("cgt",Left,Right);
899 break;
900 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000901 errs() << "Predicate = " << Predicate << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000902 llvm_unreachable("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000903 }
904}
905
906
907void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
908 const Value* Right) {
909 // FIXME: Correct comparison
910 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
911 switch (Predicate) {
912 case FCmpInst::FCMP_UGT:
913 // X > Y || llvm_fcmp_uno(X, Y)
914 printBinaryInstruction("cgt",Left,Right);
915 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
916 printSimpleInstruction("or");
917 break;
918 case FCmpInst::FCMP_OGT:
919 // X > Y
920 printBinaryInstruction("cgt",Left,Right);
921 break;
922 case FCmpInst::FCMP_UGE:
923 // X >= Y || llvm_fcmp_uno(X, Y)
924 printBinaryInstruction("ceq",Left,Right);
925 printBinaryInstruction("cgt",Left,Right);
926 printSimpleInstruction("or");
927 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
928 printSimpleInstruction("or");
929 break;
930 case FCmpInst::FCMP_OGE:
931 // X >= Y
932 printBinaryInstruction("ceq",Left,Right);
933 printBinaryInstruction("cgt",Left,Right);
934 printSimpleInstruction("or");
935 break;
936 case FCmpInst::FCMP_ULT:
937 // X < Y || llvm_fcmp_uno(X, Y)
938 printBinaryInstruction("clt",Left,Right);
939 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
940 printSimpleInstruction("or");
941 break;
942 case FCmpInst::FCMP_OLT:
943 // X < Y
944 printBinaryInstruction("clt",Left,Right);
945 break;
946 case FCmpInst::FCMP_ULE:
947 // X <= Y || llvm_fcmp_uno(X, Y)
948 printBinaryInstruction("ceq",Left,Right);
949 printBinaryInstruction("clt",Left,Right);
950 printSimpleInstruction("or");
951 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
952 printSimpleInstruction("or");
953 break;
954 case FCmpInst::FCMP_OLE:
955 // X <= Y
956 printBinaryInstruction("ceq",Left,Right);
957 printBinaryInstruction("clt",Left,Right);
958 printSimpleInstruction("or");
959 break;
960 case FCmpInst::FCMP_UEQ:
961 // X == Y || llvm_fcmp_uno(X, Y)
962 printBinaryInstruction("ceq",Left,Right);
963 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
964 printSimpleInstruction("or");
965 break;
966 case FCmpInst::FCMP_OEQ:
967 // X == Y
968 printBinaryInstruction("ceq",Left,Right);
969 break;
970 case FCmpInst::FCMP_UNE:
971 // X != Y
972 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000973 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000974 printSimpleInstruction("not");
975 break;
976 case FCmpInst::FCMP_ONE:
977 // X != Y && llvm_fcmp_ord(X, Y)
978 printBinaryInstruction("ceq",Left,Right);
979 printSimpleInstruction("not");
980 break;
981 case FCmpInst::FCMP_ORD:
982 // return X == X && Y == Y
983 printBinaryInstruction("ceq",Left,Left);
984 printBinaryInstruction("ceq",Right,Right);
985 printSimpleInstruction("or");
986 break;
987 case FCmpInst::FCMP_UNO:
988 // X != X || Y != Y
989 printBinaryInstruction("ceq",Left,Left);
990 printSimpleInstruction("not");
991 printBinaryInstruction("ceq",Right,Right);
992 printSimpleInstruction("not");
993 printSimpleInstruction("or");
994 break;
995 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000996 llvm_unreachable("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000997 }
998}
999
1000
1001void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1002 std::string Label = "leave$normal_"+utostr(getUniqID());
1003 Out << ".try {\n";
1004 // Load arguments
1005 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1006 printValueLoad(Inst->getOperand(I));
1007 // Print call instruction
1008 printFunctionCall(Inst->getOperand(0),Inst);
1009 // Save function result and leave "try" block
1010 printValueSave(Inst);
1011 printSimpleInstruction("leave",Label.c_str());
1012 Out << "}\n";
1013 Out << "catch [mscorlib]System.Exception {\n";
1014 // Redirect to unwind block
1015 printSimpleInstruction("pop");
1016 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1017 Out << "}\n" << Label << ":\n";
1018 // Redirect to continue block
1019 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1020}
1021
1022
1023void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1024 // FIXME: Emulate with IL "switch" instruction
1025 // Emulate = if () else if () else if () else ...
1026 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1027 printValueLoad(Inst->getCondition());
1028 printValueLoad(Inst->getCaseValue(I));
1029 printSimpleInstruction("ceq");
1030 // Condition jump to successor block
1031 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1032 }
1033 // Jump to default block
1034 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1035}
1036
1037
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001038void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1039 printIndirectLoad(Inst->getOperand(0));
1040 printSimpleInstruction("call",
1041 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1042 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001043 std::string Name =
Owen Anderson1d0be152009-08-13 21:58:54 +00001044 "ldind."+getTypePostfix(PointerType::getUnqual(
1045 IntegerType::get(Inst->getContext(), 8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001046 printSimpleInstruction(Name.c_str());
1047}
1048
1049
1050void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sands777d2302009-05-09 07:06:46 +00001051 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001052 // Constant optimization.
1053 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1054 printPtrLoad(CInt->getZExtValue()*Size);
1055 } else {
1056 printPtrLoad(Size);
1057 printValueLoad(Inst->getOperand(0));
1058 printSimpleInstruction("mul");
1059 }
1060 printSimpleInstruction("localloc");
1061}
1062
1063
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001064void MSILWriter::printInstruction(const Instruction* Inst) {
1065 const Value *Left = 0, *Right = 0;
1066 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1067 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1068 // Print instruction
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001069 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001070 switch (Inst->getOpcode()) {
1071 // Terminator
1072 case Instruction::Ret:
1073 if (Inst->getNumOperands()) {
1074 printValueLoad(Left);
1075 printSimpleInstruction("ret");
1076 } else
1077 printSimpleInstruction("ret");
1078 break;
1079 case Instruction::Br:
1080 printBranchInstruction(cast<BranchInst>(Inst));
1081 break;
1082 // Binary
1083 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001084 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001085 printBinaryInstruction("add",Left,Right);
1086 break;
1087 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001088 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001089 printBinaryInstruction("sub",Left,Right);
1090 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001091 case Instruction::Mul:
1092 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001093 printBinaryInstruction("mul",Left,Right);
1094 break;
1095 case Instruction::UDiv:
1096 printBinaryInstruction("div.un",Left,Right);
1097 break;
1098 case Instruction::SDiv:
1099 case Instruction::FDiv:
1100 printBinaryInstruction("div",Left,Right);
1101 break;
1102 case Instruction::URem:
1103 printBinaryInstruction("rem.un",Left,Right);
1104 break;
1105 case Instruction::SRem:
1106 case Instruction::FRem:
1107 printBinaryInstruction("rem",Left,Right);
1108 break;
1109 // Binary Condition
1110 case Instruction::ICmp:
1111 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1112 break;
1113 case Instruction::FCmp:
1114 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1115 break;
1116 // Bitwise Binary
1117 case Instruction::And:
1118 printBinaryInstruction("and",Left,Right);
1119 break;
1120 case Instruction::Or:
1121 printBinaryInstruction("or",Left,Right);
1122 break;
1123 case Instruction::Xor:
1124 printBinaryInstruction("xor",Left,Right);
1125 break;
1126 case Instruction::Shl:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001127 printValueLoad(Left);
1128 printValueLoad(Right);
1129 printSimpleInstruction("conv.i4");
1130 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001131 break;
1132 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001133 printValueLoad(Left);
1134 printValueLoad(Right);
1135 printSimpleInstruction("conv.i4");
1136 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001137 break;
1138 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001139 printValueLoad(Left);
1140 printValueLoad(Right);
1141 printSimpleInstruction("conv.i4");
1142 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001143 break;
1144 case Instruction::Select:
1145 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1146 break;
1147 case Instruction::Load:
1148 printIndirectLoad(Inst->getOperand(0));
1149 break;
1150 case Instruction::Store:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001151 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001152 break;
Anton Korobeynikov94ac0342009-07-14 09:53:14 +00001153 case Instruction::SExt:
1154 printCastInstruction(Inst->getOpcode(),Left,
1155 cast<CastInst>(Inst)->getDestTy(),
1156 cast<CastInst>(Inst)->getSrcTy());
1157 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001158 case Instruction::Trunc:
1159 case Instruction::ZExt:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001160 case Instruction::FPTrunc:
1161 case Instruction::FPExt:
1162 case Instruction::UIToFP:
1163 case Instruction::SIToFP:
1164 case Instruction::FPToUI:
1165 case Instruction::FPToSI:
1166 case Instruction::PtrToInt:
1167 case Instruction::IntToPtr:
1168 case Instruction::BitCast:
1169 printCastInstruction(Inst->getOpcode(),Left,
1170 cast<CastInst>(Inst)->getDestTy());
1171 break;
1172 case Instruction::GetElementPtr:
1173 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1174 gep_type_end(Inst));
1175 break;
1176 case Instruction::Call:
1177 printCallInstruction(cast<CallInst>(Inst));
1178 break;
1179 case Instruction::Invoke:
1180 printInvokeInstruction(cast<InvokeInst>(Inst));
1181 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001182 case Instruction::Unwind:
1183 printSimpleInstruction("newobj",
1184 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001185 printSimpleInstruction("throw");
1186 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001187 case Instruction::Switch:
1188 printSwitchInstruction(cast<SwitchInst>(Inst));
1189 break;
1190 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001191 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001192 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001193 case Instruction::Unreachable:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001194 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1195 printSimpleInstruction("newobj",
1196 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001197 printSimpleInstruction("throw");
1198 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001199 case Instruction::VAArg:
1200 printVAArgInstruction(cast<VAArgInst>(Inst));
1201 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001202 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001203 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001204 llvm_unreachable("Unsupported instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001205 }
1206}
1207
1208
1209void MSILWriter::printLoop(const Loop* L) {
1210 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1211 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1212 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1213 BasicBlock* BB = blocks[I];
1214 Loop* BBLoop = LInfo->getLoopFor(BB);
1215 if (BBLoop == L)
1216 printBasicBlock(BB);
1217 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1218 printLoop(BBLoop);
1219 }
1220 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1221}
1222
1223
1224void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1225 Out << getLabelName(BB) << ":\n";
1226 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1227 const Instruction* Inst = I;
1228 // Comment llvm original instruction
Owen Andersoncb371882008-08-21 00:14:44 +00001229 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001230 // Do not handle PHI instruction in current block
1231 if (Inst->getOpcode()==Instruction::PHI) continue;
1232 // Print instruction
1233 printInstruction(Inst);
1234 // Save result
Owen Anderson1d0be152009-08-13 21:58:54 +00001235 if (Inst->getType()!=Type::getVoidTy(BB->getContext())) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001236 // Do not save value after invoke, it done in "try" block
1237 if (Inst->getOpcode()==Instruction::Invoke) continue;
1238 printValueSave(Inst);
1239 }
1240 }
1241}
1242
1243
1244void MSILWriter::printLocalVariables(const Function& F) {
1245 std::string Name;
1246 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001247 std::set<const Value*> Printed;
1248 const Value* VaList = NULL;
1249 unsigned StackDepth = 8;
1250 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001251 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001252 if (I->getOpcode()==Instruction::Call ||
1253 I->getOpcode()==Instruction::Invoke) {
1254 // Test stack depth.
1255 if (StackDepth<I->getNumOperands())
1256 StackDepth = I->getNumOperands();
1257 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001258 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1259 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001260 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001261 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001262 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001263 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00001264 } else if (I->getType()!=Type::getVoidTy(F.getContext())) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001265 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001266 Ty = I->getType();
1267 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001268 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1269 }
1270 // Test on 'va_list' variable
1271 bool isVaList = false;
1272 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1273 // "va_list" as "va_arg" instruction operand.
1274 isVaList = true;
1275 VaList = VaInst->getOperand(0);
1276 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1277 // "va_list" as intrinsic function operand.
1278 switch (Inst->getIntrinsicID()) {
1279 case Intrinsic::vastart:
1280 case Intrinsic::vaend:
1281 case Intrinsic::vacopy:
1282 isVaList = true;
1283 VaList = Inst->getOperand(1);
1284 break;
1285 default:
1286 isVaList = false;
1287 }
1288 }
1289 // Print "va_list" variable.
1290 if (isVaList && Printed.insert(VaList).second) {
1291 Name = getValueName(VaList);
1292 Name.insert(Name.length()-1,"$valist");
1293 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1294 << Name << ")\n";
1295 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001296 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001297 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001298}
1299
1300
1301void MSILWriter::printFunctionBody(const Function& F) {
1302 // Print body
1303 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1304 if (Loop *L = LInfo->getLoopFor(I)) {
1305 if (L->getHeader()==I && L->getParentLoop()==0)
1306 printLoop(L);
1307 } else {
1308 printBasicBlock(I);
1309 }
1310 }
1311}
1312
1313
1314void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1315 const Value *left = 0, *right = 0;
1316 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1317 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1318 // Print instruction
1319 switch (CE->getOpcode()) {
1320 case Instruction::Trunc:
1321 case Instruction::ZExt:
1322 case Instruction::SExt:
1323 case Instruction::FPTrunc:
1324 case Instruction::FPExt:
1325 case Instruction::UIToFP:
1326 case Instruction::SIToFP:
1327 case Instruction::FPToUI:
1328 case Instruction::FPToSI:
1329 case Instruction::PtrToInt:
1330 case Instruction::IntToPtr:
1331 case Instruction::BitCast:
1332 printCastInstruction(CE->getOpcode(),left,CE->getType());
1333 break;
1334 case Instruction::GetElementPtr:
1335 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1336 break;
1337 case Instruction::ICmp:
1338 printICmpInstruction(CE->getPredicate(),left,right);
1339 break;
1340 case Instruction::FCmp:
1341 printFCmpInstruction(CE->getPredicate(),left,right);
1342 break;
1343 case Instruction::Select:
1344 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1345 break;
1346 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001347 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001348 printBinaryInstruction("add",left,right);
1349 break;
1350 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001351 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001352 printBinaryInstruction("sub",left,right);
1353 break;
1354 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001355 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001356 printBinaryInstruction("mul",left,right);
1357 break;
1358 case Instruction::UDiv:
1359 printBinaryInstruction("div.un",left,right);
1360 break;
1361 case Instruction::SDiv:
1362 case Instruction::FDiv:
1363 printBinaryInstruction("div",left,right);
1364 break;
1365 case Instruction::URem:
1366 printBinaryInstruction("rem.un",left,right);
1367 break;
1368 case Instruction::SRem:
1369 case Instruction::FRem:
1370 printBinaryInstruction("rem",left,right);
1371 break;
1372 case Instruction::And:
1373 printBinaryInstruction("and",left,right);
1374 break;
1375 case Instruction::Or:
1376 printBinaryInstruction("or",left,right);
1377 break;
1378 case Instruction::Xor:
1379 printBinaryInstruction("xor",left,right);
1380 break;
1381 case Instruction::Shl:
1382 printBinaryInstruction("shl",left,right);
1383 break;
1384 case Instruction::LShr:
1385 printBinaryInstruction("shr.un",left,right);
1386 break;
1387 case Instruction::AShr:
1388 printBinaryInstruction("shr",left,right);
1389 break;
1390 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001391 errs() << "Expression = " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001392 llvm_unreachable("Invalid constant expression");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001393 }
1394}
1395
1396
1397void MSILWriter::printStaticInitializerList() {
1398 // List of global variables with uninitialized fields.
1399 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1400 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1401 ++VarI) {
1402 const std::vector<StaticInitializer>& InitList = VarI->second;
1403 if (InitList.empty()) continue;
1404 // For each uninitialized field.
1405 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1406 E = InitList.end(); I!=E; ++I) {
1407 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001408 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1409 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001410 // Load variable address
1411 printValueLoad(VarI->first);
1412 // Add offset
1413 if (I->offset!=0) {
1414 printPtrLoad(I->offset);
1415 printSimpleInstruction("add");
1416 }
1417 // Load value
1418 printConstantExpr(CE);
1419 // Save result at offset
1420 std::string postfix = getTypePostfix(CE->getType(),true);
1421 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1422 postfix = "stind."+postfix;
1423 printSimpleInstruction(postfix.c_str());
1424 } else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001425 errs() << "Constant = " << *I->constant << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001426 llvm_unreachable("Invalid static initializer");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001427 }
1428 }
1429 }
1430}
1431
1432
1433void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001434 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001435 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001436 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001437 if (F.isVarArg()) Out << "vararg ";
1438 Out << getTypeName(F.getReturnType(),isSigned) <<
1439 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1440 // Arguments
1441 Out << "\t(";
1442 unsigned ArgIdx = 1;
1443 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1444 ++I, ++ArgIdx) {
Devang Patel05988662008-09-25 21:00:45 +00001445 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001446 if (I!=F.arg_begin()) Out << ", ";
1447 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1448 }
1449 Out << ") cil managed\n";
1450 // Body
1451 Out << "{\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001452 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001453 printFunctionBody(F);
1454 Out << "}\n";
1455}
1456
1457
1458void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1459 std::string Name;
1460 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001461 for (std::set<const Type*>::const_iterator
1462 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1463 const Type* Ty = *UI;
Duncan Sands1df98592010-02-16 11:11:14 +00001464 if (Ty->isArrayTy() || Ty->isVectorTy() || Ty->isStructTy())
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001465 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001466 // Type with no need to declare.
1467 else continue;
1468 // Print not duplicated type
1469 if (Printed.insert(Ty).second) {
1470 Out << ".class value explicit ansi sealed '" << Name << "'";
Duncan Sands777d2302009-05-09 07:06:46 +00001471 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001472 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001473 }
1474 }
1475}
1476
1477
1478unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1479 unsigned int N = Ty->getPrimitiveSizeInBits();
1480 assert(N!=0 && "Invalid type in getBitWidth()");
1481 switch (N) {
1482 case 1:
1483 case 8:
1484 case 16:
1485 case 32:
1486 case 64:
1487 return N;
1488 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001489 errs() << "Bits = " << N << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001490 llvm_unreachable("Unsupported integer width");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001491 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001492 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001493}
1494
1495
1496void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1497 uint64_t TySize = 0;
1498 const Type* Ty = C->getType();
1499 // Print zero initialized constant.
1500 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
Duncan Sands777d2302009-05-09 07:06:46 +00001501 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001502 Offset += TySize;
1503 Out << "int8 (0) [" << TySize << "]";
1504 return;
1505 }
1506 // Print constant initializer
1507 switch (Ty->getTypeID()) {
1508 case Type::IntegerTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001509 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001510 const ConstantInt* Int = cast<ConstantInt>(C);
1511 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1512 break;
1513 }
1514 case Type::FloatTyID:
1515 case Type::DoubleTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001516 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001517 const ConstantFP* FP = cast<ConstantFP>(C);
1518 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001519 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001520 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001521 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001522 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001523 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001524 break;
1525 }
1526 case Type::ArrayTyID:
1527 case Type::VectorTyID:
1528 case Type::StructTyID:
1529 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1530 if (I!=0) Out << ",\n";
Chris Lattner0eeb9132009-10-28 05:14:34 +00001531 printStaticConstant(cast<Constant>(C->getOperand(I)), Offset);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001532 }
1533 break;
1534 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +00001535 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001536 // Initialize with global variable address
1537 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1538 std::string name = getValueName(G);
1539 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1540 } else {
1541 // Dynamic initialization
1542 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1543 InitListPtr->push_back(StaticInitializer(C,Offset));
1544 // Null pointer initialization
1545 if (TySize==4) Out << "int32 (0)";
1546 else if (TySize==8) Out << "int64 (0)";
Torok Edwinc23197a2009-07-14 16:55:14 +00001547 else llvm_unreachable("Invalid pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001548 }
1549 break;
1550 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001551 errs() << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001552 llvm_unreachable("Invalid type in printStaticConstant()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001553 }
1554 // Increase offset.
1555 Offset += TySize;
1556}
1557
1558
1559void MSILWriter::printStaticInitializer(const Constant* C,
1560 const std::string& Name) {
1561 switch (C->getType()->getTypeID()) {
1562 case Type::IntegerTyID:
1563 case Type::FloatTyID:
1564 case Type::DoubleTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001565 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001566 break;
1567 case Type::ArrayTyID:
1568 case Type::VectorTyID:
1569 case Type::StructTyID:
1570 case Type::PointerTyID:
1571 Out << getTypeName(C->getType());
1572 break;
1573 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001574 errs() << "Type = " << *C << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001575 llvm_unreachable("Invalid constant type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001576 }
1577 // Print initializer
1578 std::string label = Name;
1579 label.insert(label.length()-1,"$data");
1580 Out << Name << " at " << label << '\n';
1581 Out << ".data " << label << " = {\n";
1582 uint64_t offset = 0;
1583 printStaticConstant(C,offset);
1584 Out << "\n}\n\n";
1585}
1586
1587
1588void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1589 const Constant* C = G->getInitializer();
1590 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1591 InitListPtr = 0;
1592 else
1593 InitListPtr = &StaticInitList[G];
1594 printStaticInitializer(C,getValueName(G));
1595}
1596
1597
1598void MSILWriter::printGlobalVariables() {
1599 if (ModulePtr->global_empty()) return;
1600 Module::global_iterator I,E;
1601 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1602 // Variable definition
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001603 Out << ".field static " << (I->isDeclaration() ? "public " :
1604 "private ");
1605 if (I->isDeclaration()) {
1606 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1607 } else
1608 printVariableDefinition(&*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001609 }
1610}
1611
1612
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001613const char* MSILWriter::getLibraryName(const Function* F) {
Daniel Dunbarbda96532009-07-21 08:57:31 +00001614 return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001615}
1616
1617
1618const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
Chris Lattner27891032010-01-16 02:15:38 +00001619 return getLibraryForSymbol(GV->getName(), false, CallingConv::C);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001620}
1621
1622
Daniel Dunbarbda96532009-07-21 08:57:31 +00001623const char* MSILWriter::getLibraryForSymbol(const StringRef &Name,
1624 bool isFunction,
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001625 CallingConv::ID CallingConv) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001626 // TODO: Read *.def file with function and libraries definitions.
1627 return "MSVCRT.DLL";
1628}
1629
1630
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001631void MSILWriter::printExternals() {
1632 Module::const_iterator I,E;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001633 // Functions.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001634 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1635 // Skip intrisics
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001636 if (I->isIntrinsic()) continue;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001637 if (I->isDeclaration()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001638 const Function* F = I;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001639 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001640 std::string Sig =
1641 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1642 Out << ".method static hidebysig pinvokeimpl(\""
1643 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001644 }
1645 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001646 // External variables and static initialization.
1647 Out <<
1648 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1649 " native int LoadLibrary(string) preservesig {}\n"
1650 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1651 " native int GetProcAddress(native int, string) preservesig {}\n";
1652 Out <<
1653 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1654 " managed cil\n{\n"
1655 "\tldarg\tlib\n"
1656 "\tcall\tnative int LoadLibrary(string)\n"
1657 "\tldarg\tsym\n"
1658 "\tcall\tnative int GetProcAddress(native int,string)\n"
1659 "\tdup\n"
1660 "\tbrtrue\tL_01\n"
1661 "\tldstr\t\"Can no import variable\"\n"
1662 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1663 "\tthrow\n"
1664 "L_01:\n"
1665 "\tret\n"
1666 "}\n\n"
1667 ".method static private void $MSIL_Init() managed cil\n{\n";
1668 printStaticInitializerList();
1669 // Foreach global variable.
1670 for (Module::global_iterator I = ModulePtr->global_begin(),
1671 E = ModulePtr->global_end(); I!=E; ++I) {
1672 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1673 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001674 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1675 printSimpleInstruction("ldsflda",Tmp.c_str());
1676 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
Chris Lattner27891032010-01-16 02:15:38 +00001677 Out << "\tldstr\t\"" << I->getName() << "\"\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001678 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1679 printIndirectSave(I->getType());
1680 }
1681 printSimpleInstruction("ret");
1682 Out << "}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001683}
1684
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001685
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001686//===----------------------------------------------------------------------===//
Bill Wendling85db3a92008-02-26 10:57:23 +00001687// External Interface declaration
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001688//===----------------------------------------------------------------------===//
1689
Dan Gohman99dca4f2010-05-11 19:57:55 +00001690bool MSILTarget::addPassesToEmitFile(PassManagerBase &PM,
1691 formatted_raw_ostream &o,
1692 CodeGenFileType FileType,
1693 CodeGenOpt::Level OptLevel,
1694 bool DisableVerify)
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001695{
Chris Lattner211edae2010-02-02 21:06:45 +00001696 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001697 MSILWriter* Writer = new MSILWriter(o);
Gordon Henriksence224772008-01-07 01:30:38 +00001698 PM.add(createGCLoweringPass());
Eric Christopher5e639902009-12-18 02:12:53 +00001699 // FIXME: Handle switch through native IL instruction "switch"
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001700 PM.add(createLowerSwitchPass());
1701 PM.add(createCFGSimplificationPass());
1702 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1703 PM.add(Writer);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001704 PM.add(createGCInfoDeleter());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001705 return false;
1706}