Add missing include (for inline PATypeHolder::get).
[oota-llvm.git] / lib / Target / ARM / AsmPrinter / ARMAsmPrinter.cpp
1 //===-- ARMAsmPrinter.cpp - Print machine code to an ARM .s file ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format ARM assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "asm-printer"
16 #include "ARM.h"
17 #include "ARMBuildAttrs.h"
18 #include "ARMAddressingModes.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMInstPrinter.h"
21 #include "ARMMachineFunctionInfo.h"
22 #include "ARMMCInstLower.h"
23 #include "ARMTargetMachine.h"
24 #include "llvm/Constants.h"
25 #include "llvm/Module.h"
26 #include "llvm/Type.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/AsmPrinter.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCContext.h"
35 #include "llvm/MC/MCInst.h"
36 #include "llvm/MC/MCSectionMachO.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Target/TargetRegistry.h"
44 #include "llvm/ADT/SmallPtrSet.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/ADT/StringSet.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/FormattedStream.h"
52 #include "llvm/Support/Mangler.h"
53 #include "llvm/Support/MathExtras.h"
54 #include <cctype>
55 using namespace llvm;
56
57 STATISTIC(EmittedInsts, "Number of machine instrs printed");
58
59 static cl::opt<bool>
60 EnableMCInst("enable-arm-mcinst-printer", cl::Hidden,
61             cl::desc("enable experimental asmprinter gunk in the arm backend"));
62
63 namespace {
64   class ARMAsmPrinter : public AsmPrinter {
65
66     /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
67     /// make the right decision when printing asm code for different targets.
68     const ARMSubtarget *Subtarget;
69
70     /// AFI - Keep a pointer to ARMFunctionInfo for the current
71     /// MachineFunction.
72     ARMFunctionInfo *AFI;
73
74     /// MCP - Keep a pointer to constantpool entries of the current
75     /// MachineFunction.
76     const MachineConstantPool *MCP;
77
78   public:
79     explicit ARMAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
80                            const MCAsmInfo *T, bool V)
81       : AsmPrinter(O, TM, T, V), AFI(NULL), MCP(NULL) {
82       Subtarget = &TM.getSubtarget<ARMSubtarget>();
83     }
84
85     virtual const char *getPassName() const {
86       return "ARM Assembly Printer";
87     }
88     
89     void printMCInst(const MCInst *MI) {
90       ARMInstPrinter(O, *MAI, VerboseAsm).printInstruction(MI);
91     }
92     
93     void printInstructionThroughMCStreamer(const MachineInstr *MI);
94     
95
96     void printOperand(const MachineInstr *MI, int OpNum,
97                       const char *Modifier = 0);
98     void printSOImmOperand(const MachineInstr *MI, int OpNum);
99     void printSOImm2PartOperand(const MachineInstr *MI, int OpNum);
100     void printSORegOperand(const MachineInstr *MI, int OpNum);
101     void printAddrMode2Operand(const MachineInstr *MI, int OpNum);
102     void printAddrMode2OffsetOperand(const MachineInstr *MI, int OpNum);
103     void printAddrMode3Operand(const MachineInstr *MI, int OpNum);
104     void printAddrMode3OffsetOperand(const MachineInstr *MI, int OpNum);
105     void printAddrMode4Operand(const MachineInstr *MI, int OpNum,
106                                const char *Modifier = 0);
107     void printAddrMode5Operand(const MachineInstr *MI, int OpNum,
108                                const char *Modifier = 0);
109     void printAddrMode6Operand(const MachineInstr *MI, int OpNum);
110     void printAddrModePCOperand(const MachineInstr *MI, int OpNum,
111                                 const char *Modifier = 0);
112     void printBitfieldInvMaskImmOperand (const MachineInstr *MI, int OpNum);
113
114     void printThumbS4ImmOperand(const MachineInstr *MI, int OpNum);
115     void printThumbITMask(const MachineInstr *MI, int OpNum);
116     void printThumbAddrModeRROperand(const MachineInstr *MI, int OpNum);
117     void printThumbAddrModeRI5Operand(const MachineInstr *MI, int OpNum,
118                                       unsigned Scale);
119     void printThumbAddrModeS1Operand(const MachineInstr *MI, int OpNum);
120     void printThumbAddrModeS2Operand(const MachineInstr *MI, int OpNum);
121     void printThumbAddrModeS4Operand(const MachineInstr *MI, int OpNum);
122     void printThumbAddrModeSPOperand(const MachineInstr *MI, int OpNum);
123
124     void printT2SOOperand(const MachineInstr *MI, int OpNum);
125     void printT2AddrModeImm12Operand(const MachineInstr *MI, int OpNum);
126     void printT2AddrModeImm8Operand(const MachineInstr *MI, int OpNum);
127     void printT2AddrModeImm8s4Operand(const MachineInstr *MI, int OpNum);
128     void printT2AddrModeImm8OffsetOperand(const MachineInstr *MI, int OpNum);
129     void printT2AddrModeSoRegOperand(const MachineInstr *MI, int OpNum);
130
131     void printPredicateOperand(const MachineInstr *MI, int OpNum);
132     void printSBitModifierOperand(const MachineInstr *MI, int OpNum);
133     void printPCLabel(const MachineInstr *MI, int OpNum);
134     void printRegisterList(const MachineInstr *MI, int OpNum);
135     void printCPInstOperand(const MachineInstr *MI, int OpNum,
136                             const char *Modifier);
137     void printJTBlockOperand(const MachineInstr *MI, int OpNum);
138     void printJT2BlockOperand(const MachineInstr *MI, int OpNum);
139     void printTBAddrMode(const MachineInstr *MI, int OpNum);
140     void printNoHashImmediate(const MachineInstr *MI, int OpNum);
141     void printVFPf32ImmOperand(const MachineInstr *MI, int OpNum);
142     void printVFPf64ImmOperand(const MachineInstr *MI, int OpNum);
143
144     void printHex8ImmOperand(const MachineInstr *MI, int OpNum) {
145       O << "#0x" << utohexstr(MI->getOperand(OpNum).getImm() & 0xff);
146     }
147     void printHex16ImmOperand(const MachineInstr *MI, int OpNum) {
148       O << "#0x" << utohexstr(MI->getOperand(OpNum).getImm() & 0xffff);
149     }
150     void printHex32ImmOperand(const MachineInstr *MI, int OpNum) {
151       O << "#0x" << utohexstr(MI->getOperand(OpNum).getImm() & 0xffffffff);
152     }
153     void printHex64ImmOperand(const MachineInstr *MI, int OpNum) {
154       O << "#0x" << utohexstr(MI->getOperand(OpNum).getImm());
155     }
156
157     virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
158                                  unsigned AsmVariant, const char *ExtraCode);
159     virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum,
160                                        unsigned AsmVariant,
161                                        const char *ExtraCode);
162
163     void PrintGlobalVariable(const GlobalVariable* GVar);
164     void printInstruction(const MachineInstr *MI);  // autogenerated.
165     static const char *getRegisterName(unsigned RegNo);
166
167     void printMachineInstruction(const MachineInstr *MI);
168     bool runOnMachineFunction(MachineFunction &F);
169     void EmitStartOfAsmFile(Module &M);
170     void EmitEndOfAsmFile(Module &M);
171
172     /// EmitMachineConstantPoolValue - Print a machine constantpool value to
173     /// the .s file.
174     virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
175       printDataDirective(MCPV->getType());
176
177       ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
178       std::string Name;
179
180       if (ACPV->isLSDA()) {
181         SmallString<16> LSDAName;
182         raw_svector_ostream(LSDAName) << MAI->getPrivateGlobalPrefix() <<
183           "_LSDA_" << getFunctionNumber();
184         Name = LSDAName.str();
185       } else if (ACPV->isBlockAddress()) {
186         Name = GetBlockAddressSymbol(ACPV->getBlockAddress())->getName();
187       } else if (ACPV->isGlobalValue()) {
188         GlobalValue *GV = ACPV->getGV();
189         bool isIndirect = Subtarget->isTargetDarwin() &&
190           Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel());
191         if (!isIndirect)
192           Name = Mang->getMangledName(GV);
193         else {
194           // FIXME: Remove this when Darwin transition to @GOT like syntax.
195           Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
196           MCSymbol *Sym = OutContext.GetOrCreateSymbol(StringRef(Name));
197           
198           MachineModuleInfoMachO &MMIMachO =
199             MMI->getObjFileInfo<MachineModuleInfoMachO>();
200           const MCSymbol *&StubSym =
201             GV->hasHiddenVisibility() ? MMIMachO.getHiddenGVStubEntry(Sym) :
202                                         MMIMachO.getGVStubEntry(Sym);
203           if (StubSym == 0) {
204             SmallString<128> NameStr;
205             Mang->getNameWithPrefix(NameStr, GV, false);
206             StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
207           }
208         }
209       } else {
210         assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
211         Name = Mang->makeNameProper(ACPV->getSymbol());
212       }
213       O << Name;
214
215       if (ACPV->hasModifier()) O << "(" << ACPV->getModifier() << ")";
216       if (ACPV->getPCAdjustment() != 0) {
217         O << "-(" << MAI->getPrivateGlobalPrefix() << "PC"
218           << getFunctionNumber() << "_"  << ACPV->getLabelId()
219           << "+" << (unsigned)ACPV->getPCAdjustment();
220          if (ACPV->mustAddCurrentAddress())
221            O << "-.";
222          O << ")";
223       }
224       O << "\n";
225     }
226
227     void getAnalysisUsage(AnalysisUsage &AU) const {
228       AsmPrinter::getAnalysisUsage(AU);
229       AU.setPreservesAll();
230       AU.addRequired<MachineModuleInfo>();
231       AU.addRequired<DwarfWriter>();
232     }
233   };
234 } // end of anonymous namespace
235
236 #include "ARMGenAsmWriter.inc"
237
238 /// runOnMachineFunction - This uses the printInstruction()
239 /// method to print assembly for each instruction.
240 ///
241 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
242   this->MF = &MF;
243
244   AFI = MF.getInfo<ARMFunctionInfo>();
245   MCP = MF.getConstantPool();
246
247   SetupMachineFunction(MF);
248   O << "\n";
249
250   // NOTE: we don't print out constant pools here, they are handled as
251   // instructions.
252
253   O << '\n';
254
255   // Print out labels for the function.
256   const Function *F = MF.getFunction();
257   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
258
259   switch (F->getLinkage()) {
260   default: llvm_unreachable("Unknown linkage type!");
261   case Function::PrivateLinkage:
262   case Function::InternalLinkage:
263     break;
264   case Function::ExternalLinkage:
265     O << "\t.globl\t" << CurrentFnName << "\n";
266     break;
267   case Function::LinkerPrivateLinkage:
268   case Function::WeakAnyLinkage:
269   case Function::WeakODRLinkage:
270   case Function::LinkOnceAnyLinkage:
271   case Function::LinkOnceODRLinkage:
272     if (Subtarget->isTargetDarwin()) {
273       O << "\t.globl\t" << CurrentFnName << "\n";
274       O << "\t.weak_definition\t" << CurrentFnName << "\n";
275     } else {
276       O << MAI->getWeakRefDirective() << CurrentFnName << "\n";
277     }
278     break;
279   }
280
281   printVisibility(CurrentFnName, F->getVisibility());
282
283   unsigned FnAlign = 1 << MF.getAlignment();  // MF alignment is log2.
284   if (AFI->isThumbFunction()) {
285     EmitAlignment(FnAlign, F, AFI->getAlign());
286     O << "\t.code\t16\n";
287     O << "\t.thumb_func";
288     if (Subtarget->isTargetDarwin())
289       O << "\t" << CurrentFnName;
290     O << "\n";
291   } else {
292     EmitAlignment(FnAlign, F);
293   }
294
295   O << CurrentFnName << ":\n";
296   // Emit pre-function debug information.
297   DW->BeginFunction(&MF);
298
299   if (Subtarget->isTargetDarwin()) {
300     // If the function is empty, then we need to emit *something*. Otherwise,
301     // the function's label might be associated with something that it wasn't
302     // meant to be associated with. We emit a noop in this situation.
303     MachineFunction::iterator I = MF.begin();
304
305     if (++I == MF.end() && MF.front().empty())
306       O << "\tnop\n";
307   }
308
309   // Print out code for the function.
310   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
311        I != E; ++I) {
312     // Print a label for the basic block.
313     if (I != MF.begin())
314       EmitBasicBlockStart(I);
315
316     // Print the assembly for the instruction.
317     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
318          II != E; ++II)
319       printMachineInstruction(II);
320   }
321
322   if (MAI->hasDotTypeDotSizeDirective())
323     O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
324
325   // Emit post-function debug information.
326   DW->EndFunction(&MF);
327
328   return false;
329 }
330
331 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
332                                  const char *Modifier) {
333   const MachineOperand &MO = MI->getOperand(OpNum);
334   unsigned TF = MO.getTargetFlags();
335
336   switch (MO.getType()) {
337   default:
338     assert(0 && "<unknown operand type>");
339   case MachineOperand::MO_Register: {
340     unsigned Reg = MO.getReg();
341     assert(TargetRegisterInfo::isPhysicalRegister(Reg));
342     if (Modifier && strcmp(Modifier, "dregpair") == 0) {
343       unsigned DRegLo = TRI->getSubReg(Reg, 5); // arm_dsubreg_0
344       unsigned DRegHi = TRI->getSubReg(Reg, 6); // arm_dsubreg_1
345       O << '{'
346         << getRegisterName(DRegLo) << ',' << getRegisterName(DRegHi)
347         << '}';
348     } else if (Modifier && strcmp(Modifier, "lane") == 0) {
349       unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(Reg);
350       unsigned DReg = TRI->getMatchingSuperReg(Reg, RegNum & 1 ? 2 : 1,
351                                                &ARM::DPR_VFP2RegClass);
352       O << getRegisterName(DReg) << '[' << (RegNum & 1) << ']';
353     } else {
354       assert(!MO.getSubReg() && "Subregs should be eliminated!");
355       O << getRegisterName(Reg);
356     }
357     break;
358   }
359   case MachineOperand::MO_Immediate: {
360     int64_t Imm = MO.getImm();
361     O << '#';
362     if ((Modifier && strcmp(Modifier, "lo16") == 0) ||
363         (TF & ARMII::MO_LO16))
364       O << ":lower16:";
365     else if ((Modifier && strcmp(Modifier, "hi16") == 0) ||
366              (TF & ARMII::MO_HI16))
367       O << ":upper16:";
368     O << Imm;
369     break;
370   }
371   case MachineOperand::MO_MachineBasicBlock:
372     GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
373     return;
374   case MachineOperand::MO_GlobalAddress: {
375     bool isCallOp = Modifier && !strcmp(Modifier, "call");
376     GlobalValue *GV = MO.getGlobal();
377
378     if ((Modifier && strcmp(Modifier, "lo16") == 0) ||
379         (TF & ARMII::MO_LO16))
380       O << ":lower16:";
381     else if ((Modifier && strcmp(Modifier, "hi16") == 0) ||
382              (TF & ARMII::MO_HI16))
383       O << ":upper16:";
384     O << Mang->getMangledName(GV);
385
386     printOffset(MO.getOffset());
387
388     if (isCallOp && Subtarget->isTargetELF() &&
389         TM.getRelocationModel() == Reloc::PIC_)
390       O << "(PLT)";
391     break;
392   }
393   case MachineOperand::MO_ExternalSymbol: {
394     bool isCallOp = Modifier && !strcmp(Modifier, "call");
395     std::string Name = Mang->makeNameProper(MO.getSymbolName());
396
397     O << Name;
398     if (isCallOp && Subtarget->isTargetELF() &&
399         TM.getRelocationModel() == Reloc::PIC_)
400       O << "(PLT)";
401     break;
402   }
403   case MachineOperand::MO_ConstantPoolIndex:
404     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
405       << '_' << MO.getIndex();
406     break;
407   case MachineOperand::MO_JumpTableIndex:
408     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
409       << '_' << MO.getIndex();
410     break;
411   }
412 }
413
414 static void printSOImm(formatted_raw_ostream &O, int64_t V, bool VerboseAsm,
415                        const MCAsmInfo *MAI) {
416   // Break it up into two parts that make up a shifter immediate.
417   V = ARM_AM::getSOImmVal(V);
418   assert(V != -1 && "Not a valid so_imm value!");
419
420   unsigned Imm = ARM_AM::getSOImmValImm(V);
421   unsigned Rot = ARM_AM::getSOImmValRot(V);
422
423   // Print low-level immediate formation info, per
424   // A5.1.3: "Data-processing operands - Immediate".
425   if (Rot) {
426     O << "#" << Imm << ", " << Rot;
427     // Pretty printed version.
428     if (VerboseAsm) {
429       O.PadToColumn(MAI->getCommentColumn());
430       O << MAI->getCommentString() << ' ';
431       O << (int)ARM_AM::rotr32(Imm, Rot);
432     }
433   } else {
434     O << "#" << Imm;
435   }
436 }
437
438 /// printSOImmOperand - SOImm is 4-bit rotate amount in bits 8-11 with 8-bit
439 /// immediate in bits 0-7.
440 void ARMAsmPrinter::printSOImmOperand(const MachineInstr *MI, int OpNum) {
441   const MachineOperand &MO = MI->getOperand(OpNum);
442   assert(MO.isImm() && "Not a valid so_imm value!");
443   printSOImm(O, MO.getImm(), VerboseAsm, MAI);
444 }
445
446 /// printSOImm2PartOperand - SOImm is broken into two pieces using a 'mov'
447 /// followed by an 'orr' to materialize.
448 void ARMAsmPrinter::printSOImm2PartOperand(const MachineInstr *MI, int OpNum) {
449   const MachineOperand &MO = MI->getOperand(OpNum);
450   assert(MO.isImm() && "Not a valid so_imm value!");
451   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO.getImm());
452   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO.getImm());
453   printSOImm(O, V1, VerboseAsm, MAI);
454   O << "\n\torr";
455   printPredicateOperand(MI, 2);
456   O << "\t";
457   printOperand(MI, 0);
458   O << ", ";
459   printOperand(MI, 0);
460   O << ", ";
461   printSOImm(O, V2, VerboseAsm, MAI);
462 }
463
464 // so_reg is a 4-operand unit corresponding to register forms of the A5.1
465 // "Addressing Mode 1 - Data-processing operands" forms.  This includes:
466 //    REG 0   0           - e.g. R5
467 //    REG REG 0,SH_OPC    - e.g. R5, ROR R3
468 //    REG 0   IMM,SH_OPC  - e.g. R5, LSL #3
469 void ARMAsmPrinter::printSORegOperand(const MachineInstr *MI, int Op) {
470   const MachineOperand &MO1 = MI->getOperand(Op);
471   const MachineOperand &MO2 = MI->getOperand(Op+1);
472   const MachineOperand &MO3 = MI->getOperand(Op+2);
473
474   O << getRegisterName(MO1.getReg());
475
476   // Print the shift opc.
477   O << ", "
478     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO3.getImm()))
479     << " ";
480
481   if (MO2.getReg()) {
482     O << getRegisterName(MO2.getReg());
483     assert(ARM_AM::getSORegOffset(MO3.getImm()) == 0);
484   } else {
485     O << "#" << ARM_AM::getSORegOffset(MO3.getImm());
486   }
487 }
488
489 void ARMAsmPrinter::printAddrMode2Operand(const MachineInstr *MI, int Op) {
490   const MachineOperand &MO1 = MI->getOperand(Op);
491   const MachineOperand &MO2 = MI->getOperand(Op+1);
492   const MachineOperand &MO3 = MI->getOperand(Op+2);
493
494   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
495     printOperand(MI, Op);
496     return;
497   }
498
499   O << "[" << getRegisterName(MO1.getReg());
500
501   if (!MO2.getReg()) {
502     if (ARM_AM::getAM2Offset(MO3.getImm()))  // Don't print +0.
503       O << ", #"
504         << (char)ARM_AM::getAM2Op(MO3.getImm())
505         << ARM_AM::getAM2Offset(MO3.getImm());
506     O << "]";
507     return;
508   }
509
510   O << ", "
511     << (char)ARM_AM::getAM2Op(MO3.getImm())
512     << getRegisterName(MO2.getReg());
513
514   if (unsigned ShImm = ARM_AM::getAM2Offset(MO3.getImm()))
515     O << ", "
516       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO3.getImm()))
517       << " #" << ShImm;
518   O << "]";
519 }
520
521 void ARMAsmPrinter::printAddrMode2OffsetOperand(const MachineInstr *MI, int Op){
522   const MachineOperand &MO1 = MI->getOperand(Op);
523   const MachineOperand &MO2 = MI->getOperand(Op+1);
524
525   if (!MO1.getReg()) {
526     unsigned ImmOffs = ARM_AM::getAM2Offset(MO2.getImm());
527     assert(ImmOffs && "Malformed indexed load / store!");
528     O << "#"
529       << (char)ARM_AM::getAM2Op(MO2.getImm())
530       << ImmOffs;
531     return;
532   }
533
534   O << (char)ARM_AM::getAM2Op(MO2.getImm())
535     << getRegisterName(MO1.getReg());
536
537   if (unsigned ShImm = ARM_AM::getAM2Offset(MO2.getImm()))
538     O << ", "
539       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO2.getImm()))
540       << " #" << ShImm;
541 }
542
543 void ARMAsmPrinter::printAddrMode3Operand(const MachineInstr *MI, int Op) {
544   const MachineOperand &MO1 = MI->getOperand(Op);
545   const MachineOperand &MO2 = MI->getOperand(Op+1);
546   const MachineOperand &MO3 = MI->getOperand(Op+2);
547
548   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
549   O << "[" << getRegisterName(MO1.getReg());
550
551   if (MO2.getReg()) {
552     O << ", "
553       << (char)ARM_AM::getAM3Op(MO3.getImm())
554       << getRegisterName(MO2.getReg())
555       << "]";
556     return;
557   }
558
559   if (unsigned ImmOffs = ARM_AM::getAM3Offset(MO3.getImm()))
560     O << ", #"
561       << (char)ARM_AM::getAM3Op(MO3.getImm())
562       << ImmOffs;
563   O << "]";
564 }
565
566 void ARMAsmPrinter::printAddrMode3OffsetOperand(const MachineInstr *MI, int Op){
567   const MachineOperand &MO1 = MI->getOperand(Op);
568   const MachineOperand &MO2 = MI->getOperand(Op+1);
569
570   if (MO1.getReg()) {
571     O << (char)ARM_AM::getAM3Op(MO2.getImm())
572       << getRegisterName(MO1.getReg());
573     return;
574   }
575
576   unsigned ImmOffs = ARM_AM::getAM3Offset(MO2.getImm());
577   assert(ImmOffs && "Malformed indexed load / store!");
578   O << "#"
579     << (char)ARM_AM::getAM3Op(MO2.getImm())
580     << ImmOffs;
581 }
582
583 void ARMAsmPrinter::printAddrMode4Operand(const MachineInstr *MI, int Op,
584                                           const char *Modifier) {
585   const MachineOperand &MO1 = MI->getOperand(Op);
586   const MachineOperand &MO2 = MI->getOperand(Op+1);
587   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO2.getImm());
588   if (Modifier && strcmp(Modifier, "submode") == 0) {
589     if (MO1.getReg() == ARM::SP) {
590       // FIXME
591       bool isLDM = (MI->getOpcode() == ARM::LDM ||
592                     MI->getOpcode() == ARM::LDM_RET ||
593                     MI->getOpcode() == ARM::t2LDM ||
594                     MI->getOpcode() == ARM::t2LDM_RET);
595       O << ARM_AM::getAMSubModeAltStr(Mode, isLDM);
596     } else
597       O << ARM_AM::getAMSubModeStr(Mode);
598   } else if (Modifier && strcmp(Modifier, "wide") == 0) {
599     ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO2.getImm());
600     if (Mode == ARM_AM::ia)
601       O << ".w";
602   } else {
603     printOperand(MI, Op);
604     if (ARM_AM::getAM4WBFlag(MO2.getImm()))
605       O << "!";
606   }
607 }
608
609 void ARMAsmPrinter::printAddrMode5Operand(const MachineInstr *MI, int Op,
610                                           const char *Modifier) {
611   const MachineOperand &MO1 = MI->getOperand(Op);
612   const MachineOperand &MO2 = MI->getOperand(Op+1);
613
614   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
615     printOperand(MI, Op);
616     return;
617   }
618
619   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
620
621   if (Modifier && strcmp(Modifier, "submode") == 0) {
622     ARM_AM::AMSubMode Mode = ARM_AM::getAM5SubMode(MO2.getImm());
623     O << ARM_AM::getAMSubModeStr(Mode);
624     return;
625   } else if (Modifier && strcmp(Modifier, "base") == 0) {
626     // Used for FSTM{D|S} and LSTM{D|S} operations.
627     O << getRegisterName(MO1.getReg());
628     if (ARM_AM::getAM5WBFlag(MO2.getImm()))
629       O << "!";
630     return;
631   }
632
633   O << "[" << getRegisterName(MO1.getReg());
634
635   if (unsigned ImmOffs = ARM_AM::getAM5Offset(MO2.getImm())) {
636     O << ", #"
637       << (char)ARM_AM::getAM5Op(MO2.getImm())
638       << ImmOffs*4;
639   }
640   O << "]";
641 }
642
643 void ARMAsmPrinter::printAddrMode6Operand(const MachineInstr *MI, int Op) {
644   const MachineOperand &MO1 = MI->getOperand(Op);
645   const MachineOperand &MO2 = MI->getOperand(Op+1);
646   const MachineOperand &MO3 = MI->getOperand(Op+2);
647   const MachineOperand &MO4 = MI->getOperand(Op+3);
648
649   O << "[" << getRegisterName(MO1.getReg());
650   if (MO4.getImm()) {
651     // FIXME: Both darwin as and GNU as violate ARM docs here.
652     O << ", :" << MO4.getImm();
653   }
654   O << "]";
655
656   if (ARM_AM::getAM6WBFlag(MO3.getImm())) {
657     if (MO2.getReg() == 0)
658       O << "!";
659     else
660       O << ", " << getRegisterName(MO2.getReg());
661   }
662 }
663
664 void ARMAsmPrinter::printAddrModePCOperand(const MachineInstr *MI, int Op,
665                                            const char *Modifier) {
666   if (Modifier && strcmp(Modifier, "label") == 0) {
667     printPCLabel(MI, Op+1);
668     return;
669   }
670
671   const MachineOperand &MO1 = MI->getOperand(Op);
672   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
673   O << "[pc, +" << getRegisterName(MO1.getReg()) << "]";
674 }
675
676 void
677 ARMAsmPrinter::printBitfieldInvMaskImmOperand(const MachineInstr *MI, int Op) {
678   const MachineOperand &MO = MI->getOperand(Op);
679   uint32_t v = ~MO.getImm();
680   int32_t lsb = CountTrailingZeros_32(v);
681   int32_t width = (32 - CountLeadingZeros_32 (v)) - lsb;
682   assert(MO.isImm() && "Not a valid bf_inv_mask_imm value!");
683   O << "#" << lsb << ", #" << width;
684 }
685
686 //===--------------------------------------------------------------------===//
687
688 void ARMAsmPrinter::printThumbS4ImmOperand(const MachineInstr *MI, int Op) {
689   O << "#" <<  MI->getOperand(Op).getImm() * 4;
690 }
691
692 void
693 ARMAsmPrinter::printThumbITMask(const MachineInstr *MI, int Op) {
694   // (3 - the number of trailing zeros) is the number of then / else.
695   unsigned Mask = MI->getOperand(Op).getImm();
696   unsigned NumTZ = CountTrailingZeros_32(Mask);
697   assert(NumTZ <= 3 && "Invalid IT mask!");
698   for (unsigned Pos = 3, e = NumTZ; Pos > e; --Pos) {
699     bool T = (Mask & (1 << Pos)) == 0;
700     if (T)
701       O << 't';
702     else
703       O << 'e';
704   }
705 }
706
707 void
708 ARMAsmPrinter::printThumbAddrModeRROperand(const MachineInstr *MI, int Op) {
709   const MachineOperand &MO1 = MI->getOperand(Op);
710   const MachineOperand &MO2 = MI->getOperand(Op+1);
711   O << "[" << getRegisterName(MO1.getReg());
712   O << ", " << getRegisterName(MO2.getReg()) << "]";
713 }
714
715 void
716 ARMAsmPrinter::printThumbAddrModeRI5Operand(const MachineInstr *MI, int Op,
717                                             unsigned Scale) {
718   const MachineOperand &MO1 = MI->getOperand(Op);
719   const MachineOperand &MO2 = MI->getOperand(Op+1);
720   const MachineOperand &MO3 = MI->getOperand(Op+2);
721
722   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
723     printOperand(MI, Op);
724     return;
725   }
726
727   O << "[" << getRegisterName(MO1.getReg());
728   if (MO3.getReg())
729     O << ", " << getRegisterName(MO3.getReg());
730   else if (unsigned ImmOffs = MO2.getImm())
731     O << ", #+" << ImmOffs * Scale;
732   O << "]";
733 }
734
735 void
736 ARMAsmPrinter::printThumbAddrModeS1Operand(const MachineInstr *MI, int Op) {
737   printThumbAddrModeRI5Operand(MI, Op, 1);
738 }
739 void
740 ARMAsmPrinter::printThumbAddrModeS2Operand(const MachineInstr *MI, int Op) {
741   printThumbAddrModeRI5Operand(MI, Op, 2);
742 }
743 void
744 ARMAsmPrinter::printThumbAddrModeS4Operand(const MachineInstr *MI, int Op) {
745   printThumbAddrModeRI5Operand(MI, Op, 4);
746 }
747
748 void ARMAsmPrinter::printThumbAddrModeSPOperand(const MachineInstr *MI,int Op) {
749   const MachineOperand &MO1 = MI->getOperand(Op);
750   const MachineOperand &MO2 = MI->getOperand(Op+1);
751   O << "[" << getRegisterName(MO1.getReg());
752   if (unsigned ImmOffs = MO2.getImm())
753     O << ", #+" << ImmOffs*4;
754   O << "]";
755 }
756
757 //===--------------------------------------------------------------------===//
758
759 // Constant shifts t2_so_reg is a 2-operand unit corresponding to the Thumb2
760 // register with shift forms.
761 // REG 0   0           - e.g. R5
762 // REG IMM, SH_OPC     - e.g. R5, LSL #3
763 void ARMAsmPrinter::printT2SOOperand(const MachineInstr *MI, int OpNum) {
764   const MachineOperand &MO1 = MI->getOperand(OpNum);
765   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
766
767   unsigned Reg = MO1.getReg();
768   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
769   O << getRegisterName(Reg);
770
771   // Print the shift opc.
772   O << ", "
773     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO2.getImm()))
774     << " ";
775
776   assert(MO2.isImm() && "Not a valid t2_so_reg value!");
777   O << "#" << ARM_AM::getSORegOffset(MO2.getImm());
778 }
779
780 void ARMAsmPrinter::printT2AddrModeImm12Operand(const MachineInstr *MI,
781                                                 int OpNum) {
782   const MachineOperand &MO1 = MI->getOperand(OpNum);
783   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
784
785   O << "[" << getRegisterName(MO1.getReg());
786
787   unsigned OffImm = MO2.getImm();
788   if (OffImm)  // Don't print +0.
789     O << ", #+" << OffImm;
790   O << "]";
791 }
792
793 void ARMAsmPrinter::printT2AddrModeImm8Operand(const MachineInstr *MI,
794                                                int OpNum) {
795   const MachineOperand &MO1 = MI->getOperand(OpNum);
796   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
797
798   O << "[" << getRegisterName(MO1.getReg());
799
800   int32_t OffImm = (int32_t)MO2.getImm();
801   // Don't print +0.
802   if (OffImm < 0)
803     O << ", #-" << -OffImm;
804   else if (OffImm > 0)
805     O << ", #+" << OffImm;
806   O << "]";
807 }
808
809 void ARMAsmPrinter::printT2AddrModeImm8s4Operand(const MachineInstr *MI,
810                                                  int OpNum) {
811   const MachineOperand &MO1 = MI->getOperand(OpNum);
812   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
813
814   O << "[" << getRegisterName(MO1.getReg());
815
816   int32_t OffImm = (int32_t)MO2.getImm() / 4;
817   // Don't print +0.
818   if (OffImm < 0)
819     O << ", #-" << -OffImm * 4;
820   else if (OffImm > 0)
821     O << ", #+" << OffImm * 4;
822   O << "]";
823 }
824
825 void ARMAsmPrinter::printT2AddrModeImm8OffsetOperand(const MachineInstr *MI,
826                                                      int OpNum) {
827   const MachineOperand &MO1 = MI->getOperand(OpNum);
828   int32_t OffImm = (int32_t)MO1.getImm();
829   // Don't print +0.
830   if (OffImm < 0)
831     O << "#-" << -OffImm;
832   else if (OffImm > 0)
833     O << "#+" << OffImm;
834 }
835
836 void ARMAsmPrinter::printT2AddrModeSoRegOperand(const MachineInstr *MI,
837                                                 int OpNum) {
838   const MachineOperand &MO1 = MI->getOperand(OpNum);
839   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
840   const MachineOperand &MO3 = MI->getOperand(OpNum+2);
841
842   O << "[" << getRegisterName(MO1.getReg());
843
844   assert(MO2.getReg() && "Invalid so_reg load / store address!");
845   O << ", " << getRegisterName(MO2.getReg());
846
847   unsigned ShAmt = MO3.getImm();
848   if (ShAmt) {
849     assert(ShAmt <= 3 && "Not a valid Thumb2 addressing mode!");
850     O << ", lsl #" << ShAmt;
851   }
852   O << "]";
853 }
854
855
856 //===--------------------------------------------------------------------===//
857
858 void ARMAsmPrinter::printPredicateOperand(const MachineInstr *MI, int OpNum) {
859   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(OpNum).getImm();
860   if (CC != ARMCC::AL)
861     O << ARMCondCodeToString(CC);
862 }
863
864 void ARMAsmPrinter::printSBitModifierOperand(const MachineInstr *MI, int OpNum){
865   unsigned Reg = MI->getOperand(OpNum).getReg();
866   if (Reg) {
867     assert(Reg == ARM::CPSR && "Expect ARM CPSR register!");
868     O << 's';
869   }
870 }
871
872 void ARMAsmPrinter::printPCLabel(const MachineInstr *MI, int OpNum) {
873   int Id = (int)MI->getOperand(OpNum).getImm();
874   O << MAI->getPrivateGlobalPrefix()
875     << "PC" << getFunctionNumber() << "_" << Id;
876 }
877
878 void ARMAsmPrinter::printRegisterList(const MachineInstr *MI, int OpNum) {
879   O << "{";
880   // Always skip the first operand, it's the optional (and implicit writeback).
881   for (unsigned i = OpNum+1, e = MI->getNumOperands(); i != e; ++i) {
882     if (MI->getOperand(i).isImplicit())
883       continue;
884     if ((int)i != OpNum+1) O << ", ";
885     printOperand(MI, i);
886   }
887   O << "}";
888 }
889
890 void ARMAsmPrinter::printCPInstOperand(const MachineInstr *MI, int OpNum,
891                                        const char *Modifier) {
892   assert(Modifier && "This operand only works with a modifier!");
893   // There are two aspects to a CONSTANTPOOL_ENTRY operand, the label and the
894   // data itself.
895   if (!strcmp(Modifier, "label")) {
896     unsigned ID = MI->getOperand(OpNum).getImm();
897     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
898       << '_' << ID << ":\n";
899   } else {
900     assert(!strcmp(Modifier, "cpentry") && "Unknown modifier for CPE");
901     unsigned CPI = MI->getOperand(OpNum).getIndex();
902
903     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
904
905     if (MCPE.isMachineConstantPoolEntry()) {
906       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
907     } else {
908       EmitGlobalConstant(MCPE.Val.ConstVal);
909     }
910   }
911 }
912
913 void ARMAsmPrinter::printJTBlockOperand(const MachineInstr *MI, int OpNum) {
914   assert(!Subtarget->isThumb2() && "Thumb2 should use double-jump jumptables!");
915
916   const MachineOperand &MO1 = MI->getOperand(OpNum);
917   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
918   unsigned JTI = MO1.getIndex();
919   O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
920     << '_' << JTI << '_' << MO2.getImm() << ":\n";
921
922   const char *JTEntryDirective = MAI->getData32bitsDirective();
923
924   const MachineFunction *MF = MI->getParent()->getParent();
925   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
926   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
927   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
928   bool UseSet= MAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_;
929   SmallPtrSet<MachineBasicBlock*, 8> JTSets;
930   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
931     MachineBasicBlock *MBB = JTBBs[i];
932     bool isNew = JTSets.insert(MBB);
933
934     if (UseSet && isNew)
935       printPICJumpTableSetLabel(JTI, MO2.getImm(), MBB);
936
937     O << JTEntryDirective << ' ';
938     if (UseSet)
939       O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
940         << '_' << JTI << '_' << MO2.getImm()
941         << "_set_" << MBB->getNumber();
942     else if (TM.getRelocationModel() == Reloc::PIC_) {
943       GetMBBSymbol(MBB->getNumber())->print(O, MAI);
944       O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
945         << getFunctionNumber() << '_' << JTI << '_' << MO2.getImm();
946     } else {
947       GetMBBSymbol(MBB->getNumber())->print(O, MAI);
948     }
949     if (i != e-1)
950       O << '\n';
951   }
952 }
953
954 void ARMAsmPrinter::printJT2BlockOperand(const MachineInstr *MI, int OpNum) {
955   const MachineOperand &MO1 = MI->getOperand(OpNum);
956   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
957   unsigned JTI = MO1.getIndex();
958   O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
959     << '_' << JTI << '_' << MO2.getImm() << ":\n";
960
961   const MachineFunction *MF = MI->getParent()->getParent();
962   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
963   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
964   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
965   bool ByteOffset = false, HalfWordOffset = false;
966   if (MI->getOpcode() == ARM::t2TBB)
967     ByteOffset = true;
968   else if (MI->getOpcode() == ARM::t2TBH)
969     HalfWordOffset = true;
970
971   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
972     MachineBasicBlock *MBB = JTBBs[i];
973     if (ByteOffset)
974       O << MAI->getData8bitsDirective();
975     else if (HalfWordOffset)
976       O << MAI->getData16bitsDirective();
977     if (ByteOffset || HalfWordOffset) {
978       O << '(';
979       GetMBBSymbol(MBB->getNumber())->print(O, MAI);
980       O << "-" << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
981         << '_' << JTI << '_' << MO2.getImm() << ")/2";
982     } else {
983       O << "\tb.w ";
984       GetMBBSymbol(MBB->getNumber())->print(O, MAI);
985     }
986     if (i != e-1)
987       O << '\n';
988   }
989
990   // Make sure the instruction that follows TBB is 2-byte aligned.
991   // FIXME: Constant island pass should insert an "ALIGN" instruction instead.
992   if (ByteOffset && (JTBBs.size() & 1)) {
993     O << '\n';
994     EmitAlignment(1);
995   }
996 }
997
998 void ARMAsmPrinter::printTBAddrMode(const MachineInstr *MI, int OpNum) {
999   O << "[pc, " << getRegisterName(MI->getOperand(OpNum).getReg());
1000   if (MI->getOpcode() == ARM::t2TBH)
1001     O << ", lsl #1";
1002   O << ']';
1003 }
1004
1005 void ARMAsmPrinter::printNoHashImmediate(const MachineInstr *MI, int OpNum) {
1006   O << MI->getOperand(OpNum).getImm();
1007 }
1008
1009 void ARMAsmPrinter::printVFPf32ImmOperand(const MachineInstr *MI, int OpNum) {
1010   const ConstantFP *FP = MI->getOperand(OpNum).getFPImm();
1011   O << '#' << FP->getValueAPF().convertToFloat();
1012   if (VerboseAsm) {
1013     O.PadToColumn(MAI->getCommentColumn());
1014     O << MAI->getCommentString() << ' ';
1015     WriteAsOperand(O, FP, /*PrintType=*/false);
1016   }
1017 }
1018
1019 void ARMAsmPrinter::printVFPf64ImmOperand(const MachineInstr *MI, int OpNum) {
1020   const ConstantFP *FP = MI->getOperand(OpNum).getFPImm();
1021   O << '#' << FP->getValueAPF().convertToDouble();
1022   if (VerboseAsm) {
1023     O.PadToColumn(MAI->getCommentColumn());
1024     O << MAI->getCommentString() << ' ';
1025     WriteAsOperand(O, FP, /*PrintType=*/false);
1026   }
1027 }
1028
1029 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
1030                                     unsigned AsmVariant, const char *ExtraCode){
1031   // Does this asm operand have a single letter operand modifier?
1032   if (ExtraCode && ExtraCode[0]) {
1033     if (ExtraCode[1] != 0) return true; // Unknown modifier.
1034
1035     switch (ExtraCode[0]) {
1036     default: return true;  // Unknown modifier.
1037     case 'a': // Print as a memory address.
1038       if (MI->getOperand(OpNum).isReg()) {
1039         O << "[" << getRegisterName(MI->getOperand(OpNum).getReg()) << "]";
1040         return false;
1041       }
1042       // Fallthrough
1043     case 'c': // Don't print "#" before an immediate operand.
1044       if (!MI->getOperand(OpNum).isImm())
1045         return true;
1046       printNoHashImmediate(MI, OpNum);
1047       return false;
1048     case 'P': // Print a VFP double precision register.
1049     case 'q': // Print a NEON quad precision register.
1050       printOperand(MI, OpNum);
1051       return false;
1052     case 'Q':
1053       if (TM.getTargetData()->isLittleEndian())
1054         break;
1055       // Fallthrough
1056     case 'R':
1057       if (TM.getTargetData()->isBigEndian())
1058         break;
1059       // Fallthrough
1060     case 'H': // Write second word of DI / DF reference.
1061       // Verify that this operand has two consecutive registers.
1062       if (!MI->getOperand(OpNum).isReg() ||
1063           OpNum+1 == MI->getNumOperands() ||
1064           !MI->getOperand(OpNum+1).isReg())
1065         return true;
1066       ++OpNum;   // Return the high-part.
1067     }
1068   }
1069
1070   printOperand(MI, OpNum);
1071   return false;
1072 }
1073
1074 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1075                                           unsigned OpNum, unsigned AsmVariant,
1076                                           const char *ExtraCode) {
1077   if (ExtraCode && ExtraCode[0])
1078     return true; // Unknown modifier.
1079
1080   const MachineOperand &MO = MI->getOperand(OpNum);
1081   assert(MO.isReg() && "unexpected inline asm memory operand");
1082   O << "[" << getRegisterName(MO.getReg()) << "]";
1083   return false;
1084 }
1085
1086 void ARMAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
1087   ++EmittedInsts;
1088
1089   // Call the autogenerated instruction printer routines.
1090   processDebugLoc(MI, true);
1091   
1092   if (EnableMCInst) {
1093     printInstructionThroughMCStreamer(MI);
1094   } else {
1095     int Opc = MI->getOpcode();
1096     if (Opc == ARM::CONSTPOOL_ENTRY)
1097       EmitAlignment(2);
1098     
1099     printInstruction(MI);
1100   }
1101   
1102   if (VerboseAsm)
1103     EmitComments(*MI);
1104   O << '\n';
1105   processDebugLoc(MI, false);
1106 }
1107
1108 void ARMAsmPrinter::EmitStartOfAsmFile(Module &M) {
1109   if (Subtarget->isTargetDarwin()) {
1110     Reloc::Model RelocM = TM.getRelocationModel();
1111     if (RelocM == Reloc::PIC_ || RelocM == Reloc::DynamicNoPIC) {
1112       // Declare all the text sections up front (before the DWARF sections
1113       // emitted by AsmPrinter::doInitialization) so the assembler will keep
1114       // them together at the beginning of the object file.  This helps
1115       // avoid out-of-range branches that are due a fundamental limitation of
1116       // the way symbol offsets are encoded with the current Darwin ARM
1117       // relocations.
1118       TargetLoweringObjectFileMachO &TLOFMacho = 
1119         static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1120       OutStreamer.SwitchSection(TLOFMacho.getTextSection());
1121       OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
1122       OutStreamer.SwitchSection(TLOFMacho.getConstTextCoalSection());
1123       if (RelocM == Reloc::DynamicNoPIC) {
1124         const MCSection *sect =
1125           TLOFMacho.getMachOSection("__TEXT", "__symbol_stub4",
1126                                     MCSectionMachO::S_SYMBOL_STUBS,
1127                                     12, SectionKind::getText());
1128         OutStreamer.SwitchSection(sect);
1129       } else {
1130         const MCSection *sect =
1131           TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub4",
1132                                     MCSectionMachO::S_SYMBOL_STUBS,
1133                                     16, SectionKind::getText());
1134         OutStreamer.SwitchSection(sect);
1135       }
1136     }
1137   }
1138
1139   // Use unified assembler syntax.
1140   O << "\t.syntax unified\n";
1141
1142   // Emit ARM Build Attributes
1143   if (Subtarget->isTargetELF()) {
1144     // CPU Type
1145     std::string CPUString = Subtarget->getCPUString();
1146     if (CPUString != "generic")
1147       O << "\t.cpu " << CPUString << '\n';
1148
1149     // FIXME: Emit FPU type
1150     if (Subtarget->hasVFP2())
1151       O << "\t.eabi_attribute " << ARMBuildAttrs::VFP_arch << ", 2\n";
1152
1153     // Signal various FP modes.
1154     if (!UnsafeFPMath)
1155       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_denormal << ", 1\n"
1156         << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_exceptions << ", 1\n";
1157
1158     if (FiniteOnlyFPMath())
1159       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_number_model << ", 1\n";
1160     else
1161       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_number_model << ", 3\n";
1162
1163     // 8-bytes alignment stuff.
1164     O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_align8_needed << ", 1\n"
1165       << "\t.eabi_attribute " << ARMBuildAttrs::ABI_align8_preserved << ", 1\n";
1166
1167     // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
1168     if (Subtarget->isAAPCS_ABI() && FloatABIType == FloatABI::Hard)
1169       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_HardFP_use << ", 3\n"
1170         << "\t.eabi_attribute " << ARMBuildAttrs::ABI_VFP_args << ", 1\n";
1171
1172     // FIXME: Should we signal R9 usage?
1173   }
1174 }
1175
1176 void ARMAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
1177   const TargetData *TD = TM.getTargetData();
1178
1179   if (!GVar->hasInitializer())   // External global require no code
1180     return;
1181
1182   // Check to see if this is a special global used by LLVM, if so, emit it.
1183
1184   if (EmitSpecialLLVMGlobal(GVar)) {
1185     if (Subtarget->isTargetDarwin() &&
1186         TM.getRelocationModel() == Reloc::Static) {
1187       if (GVar->getName() == "llvm.global_ctors")
1188         O << ".reference .constructors_used\n";
1189       else if (GVar->getName() == "llvm.global_dtors")
1190         O << ".reference .destructors_used\n";
1191     }
1192     return;
1193   }
1194
1195   std::string name = Mang->getMangledName(GVar);
1196   Constant *C = GVar->getInitializer();
1197   const Type *Type = C->getType();
1198   unsigned Size = TD->getTypeAllocSize(Type);
1199   unsigned Align = TD->getPreferredAlignmentLog(GVar);
1200   bool isDarwin = Subtarget->isTargetDarwin();
1201
1202   printVisibility(name, GVar->getVisibility());
1203
1204   if (Subtarget->isTargetELF())
1205     O << "\t.type " << name << ",%object\n";
1206
1207   const MCSection *TheSection =
1208     getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
1209   OutStreamer.SwitchSection(TheSection);
1210
1211   // FIXME: get this stuff from section kind flags.
1212   if (C->isNullValue() && !GVar->hasSection() && !GVar->isThreadLocal() &&
1213       // Don't put things that should go in the cstring section into "comm".
1214       !TheSection->getKind().isMergeableCString()) {
1215     if (GVar->hasExternalLinkage()) {
1216       if (const char *Directive = MAI->getZeroFillDirective()) {
1217         O << "\t.globl\t" << name << "\n";
1218         O << Directive << "__DATA, __common, " << name << ", "
1219           << Size << ", " << Align << "\n";
1220         return;
1221       }
1222     }
1223
1224     if (GVar->hasLocalLinkage() || GVar->isWeakForLinker()) {
1225       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
1226
1227       if (isDarwin) {
1228         if (GVar->hasLocalLinkage()) {
1229           O << MAI->getLCOMMDirective()  << name << "," << Size
1230             << ',' << Align;
1231         } else if (GVar->hasCommonLinkage()) {
1232           O << MAI->getCOMMDirective()  << name << "," << Size
1233             << ',' << Align;
1234         } else {
1235           OutStreamer.SwitchSection(TheSection);
1236           O << "\t.globl " << name << '\n'
1237             << MAI->getWeakDefDirective() << name << '\n';
1238           EmitAlignment(Align, GVar);
1239           O << name << ":";
1240           if (VerboseAsm) {
1241             O.PadToColumn(MAI->getCommentColumn());
1242             O << MAI->getCommentString() << ' ';
1243             WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1244           }
1245           O << '\n';
1246           EmitGlobalConstant(C);
1247           return;
1248         }
1249       } else if (MAI->getLCOMMDirective() != NULL) {
1250         if (GVar->hasLocalLinkage()) {
1251           O << MAI->getLCOMMDirective() << name << "," << Size;
1252         } else {
1253           O << MAI->getCOMMDirective()  << name << "," << Size;
1254           if (MAI->getCOMMDirectiveTakesAlignment())
1255             O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1256         }
1257       } else {
1258         if (GVar->hasLocalLinkage())
1259           O << "\t.local\t" << name << "\n";
1260         O << MAI->getCOMMDirective()  << name << "," << Size;
1261         if (MAI->getCOMMDirectiveTakesAlignment())
1262           O << "," << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1263       }
1264       if (VerboseAsm) {
1265         O.PadToColumn(MAI->getCommentColumn());
1266         O << MAI->getCommentString() << ' ';
1267         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1268       }
1269       O << "\n";
1270       return;
1271     }
1272   }
1273
1274   switch (GVar->getLinkage()) {
1275   case GlobalValue::CommonLinkage:
1276   case GlobalValue::LinkOnceAnyLinkage:
1277   case GlobalValue::LinkOnceODRLinkage:
1278   case GlobalValue::WeakAnyLinkage:
1279   case GlobalValue::WeakODRLinkage:
1280   case GlobalValue::LinkerPrivateLinkage:
1281     if (isDarwin) {
1282       O << "\t.globl " << name << "\n"
1283         << "\t.weak_definition " << name << "\n";
1284     } else {
1285       O << "\t.weak " << name << "\n";
1286     }
1287     break;
1288   case GlobalValue::AppendingLinkage:
1289   // FIXME: appending linkage variables should go into a section of
1290   // their name or something.  For now, just emit them as external.
1291   case GlobalValue::ExternalLinkage:
1292     O << "\t.globl " << name << "\n";
1293     break;
1294   case GlobalValue::PrivateLinkage:
1295   case GlobalValue::InternalLinkage:
1296     break;
1297   default:
1298     llvm_unreachable("Unknown linkage type!");
1299   }
1300
1301   EmitAlignment(Align, GVar);
1302   O << name << ":";
1303   if (VerboseAsm) {
1304     O.PadToColumn(MAI->getCommentColumn());
1305     O << MAI->getCommentString() << ' ';
1306     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1307   }
1308   O << "\n";
1309   if (MAI->hasDotTypeDotSizeDirective())
1310     O << "\t.size " << name << ", " << Size << "\n";
1311
1312   EmitGlobalConstant(C);
1313   O << '\n';
1314 }
1315
1316
1317 void ARMAsmPrinter::EmitEndOfAsmFile(Module &M) {
1318   if (Subtarget->isTargetDarwin()) {
1319     // All darwin targets use mach-o.
1320     TargetLoweringObjectFileMachO &TLOFMacho =
1321       static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1322     MachineModuleInfoMachO &MMIMacho =
1323       MMI->getObjFileInfo<MachineModuleInfoMachO>();
1324
1325     O << '\n';
1326
1327     // Output non-lazy-pointers for external and common global variables.
1328     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
1329     
1330     if (!Stubs.empty()) {
1331       // Switch with ".non_lazy_symbol_pointer" directive.
1332       OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1333       EmitAlignment(2);
1334       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1335         Stubs[i].first->print(O, MAI);
1336         O << ":\n\t.indirect_symbol ";
1337         Stubs[i].second->print(O, MAI);
1338         O << "\n\t.long\t0\n";
1339       }
1340     }
1341
1342     Stubs = MMIMacho.GetHiddenGVStubList();
1343     if (!Stubs.empty()) {
1344       OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1345       EmitAlignment(2);
1346       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1347         Stubs[i].first->print(O, MAI);
1348         O << ":\n\t.long ";
1349         Stubs[i].second->print(O, MAI);
1350         O << "\n";
1351       }
1352     }
1353
1354     // Funny Darwin hack: This flag tells the linker that no global symbols
1355     // contain code that falls through to other global symbols (e.g. the obvious
1356     // implementation of multiple entry points).  If this doesn't occur, the
1357     // linker can safely perform dead code stripping.  Since LLVM never
1358     // generates code that does this, it is always safe to set.
1359     OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1360   }
1361 }
1362
1363 //===----------------------------------------------------------------------===//
1364
1365 void ARMAsmPrinter::printInstructionThroughMCStreamer(const MachineInstr *MI) {
1366   ARMMCInstLower MCInstLowering(OutContext, *Mang, *this);
1367   switch (MI->getOpcode()) {
1368   case ARM::t2MOVi32imm:
1369     assert(0 && "Should be lowered by thumb2it pass");
1370   default: break;
1371   case TargetInstrInfo::DBG_LABEL:
1372   case TargetInstrInfo::EH_LABEL:
1373   case TargetInstrInfo::GC_LABEL:
1374     printLabel(MI);
1375     return;
1376   case TargetInstrInfo::KILL:
1377     printKill(MI);
1378     return;
1379   case TargetInstrInfo::INLINEASM:
1380     printInlineAsm(MI);
1381     return;
1382   case TargetInstrInfo::IMPLICIT_DEF:
1383     printImplicitDef(MI);
1384     return;
1385   case ARM::PICADD: { // FIXME: Remove asm string from td file.
1386     // This is a pseudo op for a label + instruction sequence, which looks like:
1387     // LPC0:
1388     //     add r0, pc, r0
1389     // This adds the address of LPC0 to r0.
1390     
1391     // Emit the label.
1392     // FIXME: MOVE TO SHARED PLACE.
1393     unsigned Id = (unsigned)MI->getOperand(2).getImm();
1394     const char *Prefix = MAI->getPrivateGlobalPrefix();
1395     MCSymbol *Label =OutContext.GetOrCreateSymbol(Twine(Prefix)
1396                          + "PC" + Twine(getFunctionNumber()) + "_" + Twine(Id));
1397     OutStreamer.EmitLabel(Label);
1398     
1399     
1400     // Form and emit tha dd.
1401     MCInst AddInst;
1402     AddInst.setOpcode(ARM::ADDrr);
1403     AddInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1404     AddInst.addOperand(MCOperand::CreateReg(ARM::PC));
1405     AddInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
1406     printMCInst(&AddInst);
1407     return;
1408   }
1409   case ARM::CONSTPOOL_ENTRY: { // FIXME: Remove asm string from td file.
1410     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1411     /// in the function.  The first operand is the ID# for this instruction, the
1412     /// second is the index into the MachineConstantPool that this is, the third
1413     /// is the size in bytes of this constant pool entry.
1414     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1415     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1416
1417     EmitAlignment(2);
1418
1419     const char *Prefix = MAI->getPrivateGlobalPrefix();
1420     MCSymbol *Label = OutContext.GetOrCreateSymbol(Twine(Prefix)+"CPI"+
1421                                                    Twine(getFunctionNumber())+
1422                                                    "_"+ Twine(LabelId));
1423     OutStreamer.EmitLabel(Label);
1424
1425     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1426     if (MCPE.isMachineConstantPoolEntry())
1427       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1428     else
1429       EmitGlobalConstant(MCPE.Val.ConstVal);
1430     
1431     return;
1432   }
1433   case ARM::MOVi2pieces: { // FIXME: Remove asmstring from td file.
1434     // This is a hack that lowers as a two instruction sequence.
1435     unsigned DstReg = MI->getOperand(0).getReg();
1436     unsigned ImmVal = (unsigned)MI->getOperand(1).getImm();
1437
1438     unsigned SOImmValV1 = ARM_AM::getSOImmTwoPartFirst(ImmVal);
1439     unsigned SOImmValV2 = ARM_AM::getSOImmTwoPartSecond(ImmVal);
1440     
1441     {
1442       MCInst TmpInst;
1443       TmpInst.setOpcode(ARM::MOVi);
1444       TmpInst.addOperand(MCOperand::CreateReg(DstReg));
1445       TmpInst.addOperand(MCOperand::CreateImm(SOImmValV1));
1446       
1447       // Predicate.
1448       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1449       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(3).getReg()));
1450
1451       TmpInst.addOperand(MCOperand::CreateReg(0));          // cc_out
1452       printMCInst(&TmpInst);
1453       O << '\n';
1454     }
1455
1456     {
1457       MCInst TmpInst;
1458       TmpInst.setOpcode(ARM::ORRri);
1459       TmpInst.addOperand(MCOperand::CreateReg(DstReg));     // dstreg
1460       TmpInst.addOperand(MCOperand::CreateReg(DstReg));     // inreg
1461       TmpInst.addOperand(MCOperand::CreateImm(SOImmValV2)); // so_imm
1462       // Predicate.
1463       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1464       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(3).getReg()));
1465       
1466       TmpInst.addOperand(MCOperand::CreateReg(0));          // cc_out
1467       printMCInst(&TmpInst);
1468     }
1469     return; 
1470   }
1471   case ARM::MOVi32imm: { // FIXME: Remove asmstring from td file.
1472     // This is a hack that lowers as a two instruction sequence.
1473     unsigned DstReg = MI->getOperand(0).getReg();
1474     unsigned ImmVal = (unsigned)MI->getOperand(1).getImm();
1475     
1476     {
1477       MCInst TmpInst;
1478       TmpInst.setOpcode(ARM::MOVi16);
1479       TmpInst.addOperand(MCOperand::CreateReg(DstReg));         // dstreg
1480       TmpInst.addOperand(MCOperand::CreateImm(ImmVal & 65535)); // lower16(imm)
1481       
1482       // Predicate.
1483       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1484       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(3).getReg()));
1485       
1486       printMCInst(&TmpInst);
1487       O << '\n';
1488     }
1489     
1490     {
1491       MCInst TmpInst;
1492       TmpInst.setOpcode(ARM::MOVTi16);
1493       TmpInst.addOperand(MCOperand::CreateReg(DstReg));         // dstreg
1494       TmpInst.addOperand(MCOperand::CreateReg(DstReg));         // srcreg
1495       TmpInst.addOperand(MCOperand::CreateImm(ImmVal >> 16));   // upper16(imm)
1496       
1497       // Predicate.
1498       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1499       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(3).getReg()));
1500       
1501       printMCInst(&TmpInst);
1502     }
1503     
1504     return;
1505   }
1506   }
1507       
1508   MCInst TmpInst;
1509   MCInstLowering.Lower(MI, TmpInst);
1510   
1511   printMCInst(&TmpInst);
1512 }
1513
1514 //===----------------------------------------------------------------------===//
1515 // Target Registry Stuff
1516 //===----------------------------------------------------------------------===//
1517
1518 static MCInstPrinter *createARMMCInstPrinter(const Target &T,
1519                                              unsigned SyntaxVariant,
1520                                              const MCAsmInfo &MAI,
1521                                              raw_ostream &O) {
1522   if (SyntaxVariant == 0)
1523     return new ARMInstPrinter(O, MAI, false);
1524   return 0;
1525 }
1526
1527 // Force static initialization.
1528 extern "C" void LLVMInitializeARMAsmPrinter() {
1529   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMTarget);
1530   RegisterAsmPrinter<ARMAsmPrinter> Y(TheThumbTarget);
1531
1532   TargetRegistry::RegisterMCInstPrinter(TheARMTarget, createARMMCInstPrinter);
1533   TargetRegistry::RegisterMCInstPrinter(TheThumbTarget, createARMMCInstPrinter);
1534 }
1535