blob: a57c01a5847c9024e454f9b70174b770179e8e44 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000043#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000044#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000045#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000046using namespace llvm;
47
Chris Lattner975f5c92005-09-01 18:44:10 +000048#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000049static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000050ViewISelDAGs("view-isel-dags", cl::Hidden,
51 cl::desc("Pop up a window to show isel dags as they are selected"));
52static cl::opt<bool>
53ViewSchedDAGs("view-sched-dags", cl::Hidden,
54 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000055#else
Evan Cheng739a6a42006-01-21 02:32:06 +000056static const bool ViewISelDAGs = 0;
57static const bool ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000058#endif
59
Evan Chengc1e1d972006-01-23 07:01:07 +000060namespace {
61 cl::opt<SchedHeuristics>
62 ISHeuristic(
63 "sched",
64 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000065 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000066 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000067 clEnumValN(defaultScheduling, "default",
68 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000069 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000070 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-01-23 07:01:07 +000071 clEnumValN(simpleScheduling, "simple",
72 "Simple two pass scheduling: minimize critical path "
73 "and maximize processor utilization"),
74 clEnumValN(simpleNoItinScheduling, "simple-noitin",
75 "Simple two pass scheduling: Same as simple "
76 "except using generic latency"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000077 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000078 "Bottom up register reduction list scheduling"),
Evan Chengc1e1d972006-01-23 07:01:07 +000079 clEnumValEnd));
80} // namespace
81
Chris Lattner6f87d182006-02-22 22:37:12 +000082namespace {
83 /// RegsForValue - This struct represents the physical registers that a
84 /// particular value is assigned and the type information about the value.
85 /// This is needed because values can be promoted into larger registers and
86 /// expanded into multiple smaller registers than the value.
87 struct RegsForValue {
88 /// Regs - This list hold the register (for legal and promoted values)
89 /// or register set (for expanded values) that the value should be assigned
90 /// to.
91 std::vector<unsigned> Regs;
92
93 /// RegVT - The value type of each register.
94 ///
95 MVT::ValueType RegVT;
96
97 /// ValueVT - The value type of the LLVM value, which may be promoted from
98 /// RegVT or made from merging the two expanded parts.
99 MVT::ValueType ValueVT;
100
101 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
102
103 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
104 : RegVT(regvt), ValueVT(valuevt) {
105 Regs.push_back(Reg);
106 }
107 RegsForValue(const std::vector<unsigned> &regs,
108 MVT::ValueType regvt, MVT::ValueType valuevt)
109 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
110 }
111
112 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
113 /// this value and returns the result as a ValueVT value. This uses
114 /// Chain/Flag as the input and updates them for the output Chain/Flag.
115 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000116 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000117
118 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
119 /// specified value into the registers specified by this object. This uses
120 /// Chain/Flag as the input and updates them for the output Chain/Flag.
121 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000122 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000123
124 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
125 /// operand list. This adds the code marker and includes the number of
126 /// values added into it.
127 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000128 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000129 };
130}
Evan Chengc1e1d972006-01-23 07:01:07 +0000131
Chris Lattner7a60d912005-01-07 07:47:53 +0000132namespace llvm {
133 //===--------------------------------------------------------------------===//
134 /// FunctionLoweringInfo - This contains information that is global to a
135 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000136 class FunctionLoweringInfo {
137 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000138 TargetLowering &TLI;
139 Function &Fn;
140 MachineFunction &MF;
141 SSARegMap *RegMap;
142
143 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
144
145 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
146 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
147
148 /// ValueMap - Since we emit code for the function a basic block at a time,
149 /// we must remember which virtual registers hold the values for
150 /// cross-basic-block values.
151 std::map<const Value*, unsigned> ValueMap;
152
153 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
154 /// the entry block. This allows the allocas to be efficiently referenced
155 /// anywhere in the function.
156 std::map<const AllocaInst*, int> StaticAllocaMap;
157
158 unsigned MakeReg(MVT::ValueType VT) {
159 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
160 }
Misha Brukman835702a2005-04-21 22:36:52 +0000161
Chris Lattner7a60d912005-01-07 07:47:53 +0000162 unsigned CreateRegForValue(const Value *V) {
163 MVT::ValueType VT = TLI.getValueType(V->getType());
164 // The common case is that we will only create one register for this
165 // value. If we have that case, create and return the virtual register.
166 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000167 if (NV == 1) {
168 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +0000169 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000170 }
Misha Brukman835702a2005-04-21 22:36:52 +0000171
Chris Lattner7a60d912005-01-07 07:47:53 +0000172 // If this value is represented with multiple target registers, make sure
Chris Lattner6f87d182006-02-22 22:37:12 +0000173 // to create enough consecutive registers of the right (smaller) type.
Chris Lattner7a60d912005-01-07 07:47:53 +0000174 unsigned NT = VT-1; // Find the type to use.
175 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
176 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +0000177
Chris Lattner7a60d912005-01-07 07:47:53 +0000178 unsigned R = MakeReg((MVT::ValueType)NT);
179 for (unsigned i = 1; i != NV; ++i)
180 MakeReg((MVT::ValueType)NT);
181 return R;
182 }
Misha Brukman835702a2005-04-21 22:36:52 +0000183
Chris Lattner7a60d912005-01-07 07:47:53 +0000184 unsigned InitializeRegForValue(const Value *V) {
185 unsigned &R = ValueMap[V];
186 assert(R == 0 && "Already initialized this value register!");
187 return R = CreateRegForValue(V);
188 }
189 };
190}
191
192/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
193/// PHI nodes or outside of the basic block that defines it.
194static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
195 if (isa<PHINode>(I)) return true;
196 BasicBlock *BB = I->getParent();
197 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
198 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
199 return true;
200 return false;
201}
202
Chris Lattner6871b232005-10-30 19:42:35 +0000203/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
204/// entry block, return true.
205static bool isOnlyUsedInEntryBlock(Argument *A) {
206 BasicBlock *Entry = A->getParent()->begin();
207 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
208 if (cast<Instruction>(*UI)->getParent() != Entry)
209 return false; // Use not in entry block.
210 return true;
211}
212
Chris Lattner7a60d912005-01-07 07:47:53 +0000213FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000214 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000215 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
216
Chris Lattner6871b232005-10-30 19:42:35 +0000217 // Create a vreg for each argument register that is not dead and is used
218 // outside of the entry block for the function.
219 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
220 AI != E; ++AI)
221 if (!isOnlyUsedInEntryBlock(AI))
222 InitializeRegForValue(AI);
223
Chris Lattner7a60d912005-01-07 07:47:53 +0000224 // Initialize the mapping of values to registers. This is only set up for
225 // instruction values that are used outside of the block that defines
226 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000227 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000228 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
229 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
230 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
231 const Type *Ty = AI->getAllocatedType();
232 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000233 unsigned Align =
234 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
235 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000236
237 // If the alignment of the value is smaller than the size of the value,
238 // and if the size of the value is particularly small (<= 8 bytes),
239 // round up to the size of the value for potentially better performance.
240 //
241 // FIXME: This could be made better with a preferred alignment hook in
242 // TargetData. It serves primarily to 8-byte align doubles for X86.
243 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000244 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000245 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000246 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000247 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000248 }
249
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000250 for (; BB != EB; ++BB)
251 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000252 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
253 if (!isa<AllocaInst>(I) ||
254 !StaticAllocaMap.count(cast<AllocaInst>(I)))
255 InitializeRegForValue(I);
256
257 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
258 // also creates the initial PHI MachineInstrs, though none of the input
259 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000260 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000261 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
262 MBBMap[BB] = MBB;
263 MF.getBasicBlockList().push_back(MBB);
264
265 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
266 // appropriate.
267 PHINode *PN;
268 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000269 (PN = dyn_cast<PHINode>(I)); ++I)
270 if (!PN->use_empty()) {
271 unsigned NumElements =
272 TLI.getNumElements(TLI.getValueType(PN->getType()));
273 unsigned PHIReg = ValueMap[PN];
274 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
275 for (unsigned i = 0; i != NumElements; ++i)
276 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
277 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000278 }
279}
280
281
282
283//===----------------------------------------------------------------------===//
284/// SelectionDAGLowering - This is the common target-independent lowering
285/// implementation that is parameterized by a TargetLowering object.
286/// Also, targets can overload any lowering method.
287///
288namespace llvm {
289class SelectionDAGLowering {
290 MachineBasicBlock *CurMBB;
291
292 std::map<const Value*, SDOperand> NodeMap;
293
Chris Lattner4d9651c2005-01-17 22:19:26 +0000294 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
295 /// them up and then emit token factor nodes when possible. This allows us to
296 /// get simple disambiguation between loads without worrying about alias
297 /// analysis.
298 std::vector<SDOperand> PendingLoads;
299
Chris Lattner7a60d912005-01-07 07:47:53 +0000300public:
301 // TLI - This is information that describes the available target features we
302 // need for lowering. This indicates when operations are unavailable,
303 // implemented with a libcall, etc.
304 TargetLowering &TLI;
305 SelectionDAG &DAG;
306 const TargetData &TD;
307
308 /// FuncInfo - Information about the function as a whole.
309 ///
310 FunctionLoweringInfo &FuncInfo;
311
312 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000313 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000314 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
315 FuncInfo(funcinfo) {
316 }
317
Chris Lattner4108bb02005-01-17 19:43:36 +0000318 /// getRoot - Return the current virtual root of the Selection DAG.
319 ///
320 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000321 if (PendingLoads.empty())
322 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000323
Chris Lattner4d9651c2005-01-17 22:19:26 +0000324 if (PendingLoads.size() == 1) {
325 SDOperand Root = PendingLoads[0];
326 DAG.setRoot(Root);
327 PendingLoads.clear();
328 return Root;
329 }
330
331 // Otherwise, we have to make a token factor node.
332 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
333 PendingLoads.clear();
334 DAG.setRoot(Root);
335 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000336 }
337
Chris Lattner7a60d912005-01-07 07:47:53 +0000338 void visit(Instruction &I) { visit(I.getOpcode(), I); }
339
340 void visit(unsigned Opcode, User &I) {
341 switch (Opcode) {
342 default: assert(0 && "Unknown instruction type encountered!");
343 abort();
344 // Build the switch statement using the Instruction.def file.
345#define HANDLE_INST(NUM, OPCODE, CLASS) \
346 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
347#include "llvm/Instruction.def"
348 }
349 }
350
351 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
352
353
354 SDOperand getIntPtrConstant(uint64_t Val) {
355 return DAG.getConstant(Val, TLI.getPointerTy());
356 }
357
358 SDOperand getValue(const Value *V) {
359 SDOperand &N = NodeMap[V];
360 if (N.Val) return N;
361
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000362 const Type *VTy = V->getType();
363 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner7a60d912005-01-07 07:47:53 +0000364 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
365 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
366 visit(CE->getOpcode(), *CE);
367 assert(N.Val && "visit didn't populate the ValueMap!");
368 return N;
369 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
370 return N = DAG.getGlobalAddress(GV, VT);
371 } else if (isa<ConstantPointerNull>(C)) {
372 return N = DAG.getConstant(0, TLI.getPointerTy());
373 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000374 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000375 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
376 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000377 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
378 unsigned NumElements = PTy->getNumElements();
379 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
380 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
381
382 // Now that we know the number and type of the elements, push a
383 // Constant or ConstantFP node onto the ops list for each element of
384 // the packed constant.
385 std::vector<SDOperand> Ops;
Chris Lattner803a5752005-12-21 02:43:26 +0000386 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
387 if (MVT::isFloatingPoint(PVT)) {
388 for (unsigned i = 0; i != NumElements; ++i) {
389 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
390 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
391 }
392 } else {
393 for (unsigned i = 0; i != NumElements; ++i) {
394 const ConstantIntegral *El =
395 cast<ConstantIntegral>(CP->getOperand(i));
396 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
397 }
398 }
399 } else {
400 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
401 SDOperand Op;
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000402 if (MVT::isFloatingPoint(PVT))
Chris Lattner803a5752005-12-21 02:43:26 +0000403 Op = DAG.getConstantFP(0, PVT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000404 else
Chris Lattner803a5752005-12-21 02:43:26 +0000405 Op = DAG.getConstant(0, PVT);
406 Ops.assign(NumElements, Op);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000407 }
Chris Lattner803a5752005-12-21 02:43:26 +0000408
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000409 // Handle the case where we have a 1-element vector, in which
410 // case we want to immediately turn it into a scalar constant.
Nate Begemanae89d862005-12-07 19:48:11 +0000411 if (Ops.size() == 1) {
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000412 return N = Ops[0];
Nate Begemanae89d862005-12-07 19:48:11 +0000413 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
414 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
415 } else {
416 // If the packed type isn't legal, then create a ConstantVec node with
417 // generic Vector type instead.
418 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
419 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000420 } else {
421 // Canonicalize all constant ints to be unsigned.
422 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
423 }
424
425 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
426 std::map<const AllocaInst*, int>::iterator SI =
427 FuncInfo.StaticAllocaMap.find(AI);
428 if (SI != FuncInfo.StaticAllocaMap.end())
429 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
430 }
431
432 std::map<const Value*, unsigned>::const_iterator VMI =
433 FuncInfo.ValueMap.find(V);
434 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000435
Chris Lattner33182322005-08-16 21:55:35 +0000436 unsigned InReg = VMI->second;
437
438 // If this type is not legal, make it so now.
439 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
440
441 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
442 if (DestVT < VT) {
443 // Source must be expanded. This input value is actually coming from the
444 // register pair VMI->second and VMI->second+1.
445 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
446 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
447 } else {
448 if (DestVT > VT) { // Promotion case
449 if (MVT::isFloatingPoint(VT))
450 N = DAG.getNode(ISD::FP_ROUND, VT, N);
451 else
452 N = DAG.getNode(ISD::TRUNCATE, VT, N);
453 }
454 }
455
456 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000457 }
458
459 const SDOperand &setValue(const Value *V, SDOperand NewN) {
460 SDOperand &N = NodeMap[V];
461 assert(N.Val == 0 && "Already set a value for this node!");
462 return N = NewN;
463 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000464
Chris Lattner6f87d182006-02-22 22:37:12 +0000465 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
466 MVT::ValueType VT,
467 bool OutReg, bool InReg,
468 std::set<unsigned> &OutputRegs,
469 std::set<unsigned> &InputRegs);
470
Chris Lattner7a60d912005-01-07 07:47:53 +0000471 // Terminator instructions.
472 void visitRet(ReturnInst &I);
473 void visitBr(BranchInst &I);
474 void visitUnreachable(UnreachableInst &I) { /* noop */ }
475
476 // These all get lowered before this pass.
Robert Bocchino2c966e72006-01-10 19:04:57 +0000477 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino03e95af2006-01-17 20:06:42 +0000478 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000479 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
480 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
481 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
482
483 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000484 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000485 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000486 void visitAdd(User &I) {
487 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000488 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000489 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000490 void visitMul(User &I) {
491 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000492 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000493 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000494 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000495 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000496 }
497 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000498 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000499 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000500 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000501 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
502 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
503 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begeman127321b2005-11-18 07:42:56 +0000504 void visitShl(User &I) { visitShift(I, ISD::SHL); }
505 void visitShr(User &I) {
506 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000507 }
508
509 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
510 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
511 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
512 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
513 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
514 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
515 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
516
517 void visitGetElementPtr(User &I);
518 void visitCast(User &I);
519 void visitSelect(User &I);
520 //
521
522 void visitMalloc(MallocInst &I);
523 void visitFree(FreeInst &I);
524 void visitAlloca(AllocaInst &I);
525 void visitLoad(LoadInst &I);
526 void visitStore(StoreInst &I);
527 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
528 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000529 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000530 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000531
Chris Lattner7a60d912005-01-07 07:47:53 +0000532 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000533 void visitVAArg(VAArgInst &I);
534 void visitVAEnd(CallInst &I);
535 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000536 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000537
Chris Lattner875def92005-01-11 05:56:49 +0000538 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000539
540 void visitUserOp1(Instruction &I) {
541 assert(0 && "UserOp1 should not exist at instruction selection time!");
542 abort();
543 }
544 void visitUserOp2(Instruction &I) {
545 assert(0 && "UserOp2 should not exist at instruction selection time!");
546 abort();
547 }
548};
549} // end namespace llvm
550
551void SelectionDAGLowering::visitRet(ReturnInst &I) {
552 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000553 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000554 return;
555 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000556 std::vector<SDOperand> NewValues;
557 NewValues.push_back(getRoot());
558 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
559 SDOperand RetOp = getValue(I.getOperand(i));
560
561 // If this is an integer return value, we need to promote it ourselves to
562 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
563 // than sign/zero.
564 if (MVT::isInteger(RetOp.getValueType()) &&
565 RetOp.getValueType() < MVT::i64) {
566 MVT::ValueType TmpVT;
567 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
568 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
569 else
570 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000571
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000572 if (I.getOperand(i)->getType()->isSigned())
573 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
574 else
575 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
576 }
577 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000578 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000579 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000580}
581
582void SelectionDAGLowering::visitBr(BranchInst &I) {
583 // Update machine-CFG edges.
584 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000585
586 // Figure out which block is immediately after the current one.
587 MachineBasicBlock *NextBlock = 0;
588 MachineFunction::iterator BBI = CurMBB;
589 if (++BBI != CurMBB->getParent()->end())
590 NextBlock = BBI;
591
592 if (I.isUnconditional()) {
593 // If this is not a fall-through branch, emit the branch.
594 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000595 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000596 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000597 } else {
598 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000599
600 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000601 if (Succ1MBB == NextBlock) {
602 // If the condition is false, fall through. This means we should branch
603 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000604 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000605 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000606 } else if (Succ0MBB == NextBlock) {
607 // If the condition is true, fall through. This means we should branch if
608 // the condition is false to Succ #1. Invert the condition first.
609 SDOperand True = DAG.getConstant(1, Cond.getValueType());
610 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000611 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000612 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000613 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000614 std::vector<SDOperand> Ops;
615 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000616 // If the false case is the current basic block, then this is a self
617 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
618 // adds an extra instruction in the loop. Instead, invert the
619 // condition and emit "Loop: ... br!cond Loop; br Out.
620 if (CurMBB == Succ1MBB) {
621 std::swap(Succ0MBB, Succ1MBB);
622 SDOperand True = DAG.getConstant(1, Cond.getValueType());
623 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
624 }
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000625 Ops.push_back(Cond);
626 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
627 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
628 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000629 }
630 }
631}
632
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000633void SelectionDAGLowering::visitSub(User &I) {
634 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000635 if (I.getType()->isFloatingPoint()) {
636 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
637 if (CFP->isExactlyValue(-0.0)) {
638 SDOperand Op2 = getValue(I.getOperand(1));
639 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
640 return;
641 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000642 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000643 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000644}
645
Nate Begemanb2e089c2005-11-19 00:36:38 +0000646void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
647 unsigned VecOp) {
648 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000649 SDOperand Op1 = getValue(I.getOperand(0));
650 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000651
Chris Lattner19baba62005-11-19 18:40:42 +0000652 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000653 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
654 } else if (Ty->isFloatingPoint()) {
655 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
656 } else {
657 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000658 unsigned NumElements = PTy->getNumElements();
659 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000660 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000661
662 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000663 // the Legalize pass does not have to deal with them. Similarly, if the
664 // abstract vector is going to turn into one that the target natively
665 // supports, generate that type now so that Legalize doesn't have to deal
666 // with that either. These steps ensure that Legalize only has to handle
667 // vector types in its Expand case.
668 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000669 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000670 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000671 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
672 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000673 } else {
674 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
675 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemand37c1312005-11-22 18:16:00 +0000676 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman07890bb2005-11-22 01:29:36 +0000677 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000678 }
Nate Begeman127321b2005-11-18 07:42:56 +0000679}
Chris Lattner96c26752005-01-19 22:31:21 +0000680
Nate Begeman127321b2005-11-18 07:42:56 +0000681void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
682 SDOperand Op1 = getValue(I.getOperand(0));
683 SDOperand Op2 = getValue(I.getOperand(1));
684
685 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
686
Chris Lattner7a60d912005-01-07 07:47:53 +0000687 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
688}
689
690void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
691 ISD::CondCode UnsignedOpcode) {
692 SDOperand Op1 = getValue(I.getOperand(0));
693 SDOperand Op2 = getValue(I.getOperand(1));
694 ISD::CondCode Opcode = SignedOpcode;
695 if (I.getOperand(0)->getType()->isUnsigned())
696 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000697 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000698}
699
700void SelectionDAGLowering::visitSelect(User &I) {
701 SDOperand Cond = getValue(I.getOperand(0));
702 SDOperand TrueVal = getValue(I.getOperand(1));
703 SDOperand FalseVal = getValue(I.getOperand(2));
704 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
705 TrueVal, FalseVal));
706}
707
708void SelectionDAGLowering::visitCast(User &I) {
709 SDOperand N = getValue(I.getOperand(0));
710 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
711 MVT::ValueType DestTy = TLI.getValueType(I.getType());
712
713 if (N.getValueType() == DestTy) {
714 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000715 } else if (DestTy == MVT::i1) {
716 // Cast to bool is a comparison against zero, not truncation to zero.
717 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
718 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000719 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000720 } else if (isInteger(SrcTy)) {
721 if (isInteger(DestTy)) { // Int -> Int cast
722 if (DestTy < SrcTy) // Truncating cast?
723 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
724 else if (I.getOperand(0)->getType()->isSigned())
725 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
726 else
727 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
728 } else { // Int -> FP cast
729 if (I.getOperand(0)->getType()->isSigned())
730 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
731 else
732 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
733 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000734 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000735 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
736 if (isFloatingPoint(DestTy)) { // FP -> FP cast
737 if (DestTy < SrcTy) // Rounding cast?
738 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
739 else
740 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
741 } else { // FP -> Int cast.
742 if (I.getType()->isSigned())
743 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
744 else
745 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
746 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000747 }
748}
749
750void SelectionDAGLowering::visitGetElementPtr(User &I) {
751 SDOperand N = getValue(I.getOperand(0));
752 const Type *Ty = I.getOperand(0)->getType();
753 const Type *UIntPtrTy = TD.getIntPtrType();
754
755 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
756 OI != E; ++OI) {
757 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000758 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000759 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
760 if (Field) {
761 // N = N + Offset
762 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
763 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000764 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000765 }
766 Ty = StTy->getElementType(Field);
767 } else {
768 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000769
Chris Lattner43535a12005-11-09 04:45:33 +0000770 // If this is a constant subscript, handle it quickly.
771 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
772 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000773
Chris Lattner43535a12005-11-09 04:45:33 +0000774 uint64_t Offs;
775 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
776 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
777 else
778 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
779 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
780 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000781 }
Chris Lattner43535a12005-11-09 04:45:33 +0000782
783 // N = N + Idx * ElementSize;
784 uint64_t ElementSize = TD.getTypeSize(Ty);
785 SDOperand IdxN = getValue(Idx);
786
787 // If the index is smaller or larger than intptr_t, truncate or extend
788 // it.
789 if (IdxN.getValueType() < N.getValueType()) {
790 if (Idx->getType()->isSigned())
791 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
792 else
793 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
794 } else if (IdxN.getValueType() > N.getValueType())
795 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
796
797 // If this is a multiply by a power of two, turn it into a shl
798 // immediately. This is a very common case.
799 if (isPowerOf2_64(ElementSize)) {
800 unsigned Amt = Log2_64(ElementSize);
801 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000802 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000803 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
804 continue;
805 }
806
807 SDOperand Scale = getIntPtrConstant(ElementSize);
808 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
809 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000810 }
811 }
812 setValue(&I, N);
813}
814
815void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
816 // If this is a fixed sized alloca in the entry block of the function,
817 // allocate it statically on the stack.
818 if (FuncInfo.StaticAllocaMap.count(&I))
819 return; // getValue will auto-populate this.
820
821 const Type *Ty = I.getAllocatedType();
822 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000823 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
824 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000825
826 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000827 MVT::ValueType IntPtr = TLI.getPointerTy();
828 if (IntPtr < AllocSize.getValueType())
829 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
830 else if (IntPtr > AllocSize.getValueType())
831 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000832
Chris Lattnereccb73d2005-01-22 23:04:37 +0000833 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000834 getIntPtrConstant(TySize));
835
836 // Handle alignment. If the requested alignment is less than or equal to the
837 // stack alignment, ignore it and round the size of the allocation up to the
838 // stack alignment size. If the size is greater than the stack alignment, we
839 // note this in the DYNAMIC_STACKALLOC node.
840 unsigned StackAlign =
841 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
842 if (Align <= StackAlign) {
843 Align = 0;
844 // Add SA-1 to the size.
845 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
846 getIntPtrConstant(StackAlign-1));
847 // Mask out the low bits for alignment purposes.
848 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
849 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
850 }
851
Chris Lattner96c262e2005-05-14 07:29:57 +0000852 std::vector<MVT::ValueType> VTs;
853 VTs.push_back(AllocSize.getValueType());
854 VTs.push_back(MVT::Other);
855 std::vector<SDOperand> Ops;
856 Ops.push_back(getRoot());
857 Ops.push_back(AllocSize);
858 Ops.push_back(getIntPtrConstant(Align));
859 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000860 DAG.setRoot(setValue(&I, DSA).getValue(1));
861
862 // Inform the Frame Information that we have just allocated a variable-sized
863 // object.
864 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
865}
866
Chris Lattner435b4022005-11-29 06:21:05 +0000867/// getStringValue - Turn an LLVM constant pointer that eventually points to a
868/// global into a string value. Return an empty string if we can't do it.
869///
Evan Cheng6781b6e2006-02-15 21:59:04 +0000870static std::string getStringValue(GlobalVariable *GV, unsigned Offset = 0) {
871 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
872 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
873 if (Init->isString()) {
874 std::string Result = Init->getAsString();
875 if (Offset < Result.size()) {
876 // If we are pointing INTO The string, erase the beginning...
877 Result.erase(Result.begin(), Result.begin()+Offset);
878 return Result;
Chris Lattner435b4022005-11-29 06:21:05 +0000879 }
880 }
881 }
882 return "";
883}
Chris Lattner7a60d912005-01-07 07:47:53 +0000884
885void SelectionDAGLowering::visitLoad(LoadInst &I) {
886 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000887
Chris Lattner4d9651c2005-01-17 22:19:26 +0000888 SDOperand Root;
889 if (I.isVolatile())
890 Root = getRoot();
891 else {
892 // Do not serialize non-volatile loads against each other.
893 Root = DAG.getRoot();
894 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000895
896 const Type *Ty = I.getType();
897 SDOperand L;
898
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000899 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000900 unsigned NumElements = PTy->getNumElements();
901 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000902 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000903
904 // Immediately scalarize packed types containing only one element, so that
905 // the Legalize pass does not have to deal with them.
906 if (NumElements == 1) {
907 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000908 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
909 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman07890bb2005-11-22 01:29:36 +0000910 } else {
911 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
912 DAG.getSrcValue(I.getOperand(0)));
913 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000914 } else {
915 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
916 DAG.getSrcValue(I.getOperand(0)));
917 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000918 setValue(&I, L);
919
920 if (I.isVolatile())
921 DAG.setRoot(L.getValue(1));
922 else
923 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000924}
925
926
927void SelectionDAGLowering::visitStore(StoreInst &I) {
928 Value *SrcV = I.getOperand(0);
929 SDOperand Src = getValue(SrcV);
930 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000931 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000932 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000933}
934
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000935/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
936/// we want to emit this as a call to a named external function, return the name
937/// otherwise lower it and return null.
938const char *
939SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
940 switch (Intrinsic) {
941 case Intrinsic::vastart: visitVAStart(I); return 0;
942 case Intrinsic::vaend: visitVAEnd(I); return 0;
943 case Intrinsic::vacopy: visitVACopy(I); return 0;
944 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
945 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
946 case Intrinsic::setjmp:
947 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
948 break;
949 case Intrinsic::longjmp:
950 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
951 break;
952 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
953 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
954 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
955
956 case Intrinsic::readport:
957 case Intrinsic::readio: {
958 std::vector<MVT::ValueType> VTs;
959 VTs.push_back(TLI.getValueType(I.getType()));
960 VTs.push_back(MVT::Other);
961 std::vector<SDOperand> Ops;
962 Ops.push_back(getRoot());
963 Ops.push_back(getValue(I.getOperand(1)));
964 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
965 ISD::READPORT : ISD::READIO, VTs, Ops);
966
967 setValue(&I, Tmp);
968 DAG.setRoot(Tmp.getValue(1));
969 return 0;
970 }
971 case Intrinsic::writeport:
972 case Intrinsic::writeio:
973 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
974 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
975 getRoot(), getValue(I.getOperand(1)),
976 getValue(I.getOperand(2))));
977 return 0;
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000978
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000979 case Intrinsic::dbg_stoppoint: {
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000980 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
981 return "llvm_debugger_stop";
Chris Lattner435b4022005-11-29 06:21:05 +0000982
Jim Laskey5995d012006-02-11 01:01:30 +0000983 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
984 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) {
985 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +0000986
Jim Laskey5995d012006-02-11 01:01:30 +0000987 // Input Chain
988 Ops.push_back(getRoot());
989
990 // line number
991 Ops.push_back(getValue(I.getOperand(2)));
992
993 // column
994 Ops.push_back(getValue(I.getOperand(3)));
Chris Lattner435b4022005-11-29 06:21:05 +0000995
Jim Laskey390c63e2006-02-13 12:50:39 +0000996 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
Jim Laskey5995d012006-02-11 01:01:30 +0000997 assert(DD && "Not a debug information descriptor");
998 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
999 assert(CompileUnit && "Not a compile unit");
1000 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1001 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1002
1003 if (Ops.size() == 5) // Found filename/workingdir.
1004 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001005 }
1006
Chris Lattner8782b782005-12-03 18:50:48 +00001007 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001008 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001009 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001010 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001011 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1012 return "llvm_dbg_region_start";
1013 if (I.getType() != Type::VoidTy)
1014 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1015 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001016 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001017 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1018 return "llvm_dbg_region_end";
1019 if (I.getType() != Type::VoidTy)
1020 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1021 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001022 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001023 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1024 return "llvm_dbg_subprogram";
1025 if (I.getType() != Type::VoidTy)
1026 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1027 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001028 case Intrinsic::dbg_declare:
1029 if (I.getType() != Type::VoidTy)
1030 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1031 return 0;
1032
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001033 case Intrinsic::isunordered_f32:
1034 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001035 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1036 getValue(I.getOperand(2)), ISD::SETUO));
1037 return 0;
1038
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001039 case Intrinsic::sqrt_f32:
1040 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001041 setValue(&I, DAG.getNode(ISD::FSQRT,
1042 getValue(I.getOperand(1)).getValueType(),
1043 getValue(I.getOperand(1))));
1044 return 0;
1045 case Intrinsic::pcmarker: {
1046 SDOperand Tmp = getValue(I.getOperand(1));
1047 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1048 return 0;
1049 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001050 case Intrinsic::readcyclecounter: {
1051 std::vector<MVT::ValueType> VTs;
1052 VTs.push_back(MVT::i64);
1053 VTs.push_back(MVT::Other);
1054 std::vector<SDOperand> Ops;
1055 Ops.push_back(getRoot());
1056 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1057 setValue(&I, Tmp);
1058 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001059 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001060 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001061 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001062 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001063 case Intrinsic::bswap_i64:
1064 setValue(&I, DAG.getNode(ISD::BSWAP,
1065 getValue(I.getOperand(1)).getValueType(),
1066 getValue(I.getOperand(1))));
1067 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001068 case Intrinsic::cttz_i8:
1069 case Intrinsic::cttz_i16:
1070 case Intrinsic::cttz_i32:
1071 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001072 setValue(&I, DAG.getNode(ISD::CTTZ,
1073 getValue(I.getOperand(1)).getValueType(),
1074 getValue(I.getOperand(1))));
1075 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001076 case Intrinsic::ctlz_i8:
1077 case Intrinsic::ctlz_i16:
1078 case Intrinsic::ctlz_i32:
1079 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001080 setValue(&I, DAG.getNode(ISD::CTLZ,
1081 getValue(I.getOperand(1)).getValueType(),
1082 getValue(I.getOperand(1))));
1083 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001084 case Intrinsic::ctpop_i8:
1085 case Intrinsic::ctpop_i16:
1086 case Intrinsic::ctpop_i32:
1087 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001088 setValue(&I, DAG.getNode(ISD::CTPOP,
1089 getValue(I.getOperand(1)).getValueType(),
1090 getValue(I.getOperand(1))));
1091 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001092 case Intrinsic::stacksave: {
1093 std::vector<MVT::ValueType> VTs;
1094 VTs.push_back(TLI.getPointerTy());
1095 VTs.push_back(MVT::Other);
1096 std::vector<SDOperand> Ops;
1097 Ops.push_back(getRoot());
1098 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1099 setValue(&I, Tmp);
1100 DAG.setRoot(Tmp.getValue(1));
1101 return 0;
1102 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001103 case Intrinsic::stackrestore: {
1104 SDOperand Tmp = getValue(I.getOperand(1));
1105 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001106 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001107 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001108 case Intrinsic::prefetch:
1109 // FIXME: Currently discarding prefetches.
1110 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001111 default:
1112 std::cerr << I;
1113 assert(0 && "This intrinsic is not implemented yet!");
1114 return 0;
1115 }
1116}
1117
1118
Chris Lattner7a60d912005-01-07 07:47:53 +00001119void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001120 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001121 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001122 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001123 if (unsigned IID = F->getIntrinsicID()) {
1124 RenameFn = visitIntrinsicCall(I, IID);
1125 if (!RenameFn)
1126 return;
1127 } else { // Not an LLVM intrinsic.
1128 const std::string &Name = F->getName();
1129 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001130 if (I.getNumOperands() == 2 && // Basic sanity checks.
1131 I.getOperand(1)->getType()->isFloatingPoint() &&
1132 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001133 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001134 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1135 return;
1136 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001137 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001138 if (I.getNumOperands() == 2 && // Basic sanity checks.
1139 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001140 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001141 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001142 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1143 return;
1144 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001145 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001146 if (I.getNumOperands() == 2 && // Basic sanity checks.
1147 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001148 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001149 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001150 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1151 return;
1152 }
1153 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001154 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001155 } else if (isa<InlineAsm>(I.getOperand(0))) {
1156 visitInlineAsm(I);
1157 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001158 }
Misha Brukman835702a2005-04-21 22:36:52 +00001159
Chris Lattner18d2b342005-01-08 22:48:57 +00001160 SDOperand Callee;
1161 if (!RenameFn)
1162 Callee = getValue(I.getOperand(0));
1163 else
1164 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001165 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001166 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001167 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1168 Value *Arg = I.getOperand(i);
1169 SDOperand ArgNode = getValue(Arg);
1170 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1171 }
Misha Brukman835702a2005-04-21 22:36:52 +00001172
Nate Begemanf6565252005-03-26 01:29:23 +00001173 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1174 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001175
Chris Lattner1f45cd72005-01-08 19:26:18 +00001176 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001177 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001178 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001179 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001180 setValue(&I, Result.first);
1181 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001182}
1183
Chris Lattner6f87d182006-02-22 22:37:12 +00001184SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001185 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001186 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1187 Chain = Val.getValue(1);
1188 Flag = Val.getValue(2);
1189
1190 // If the result was expanded, copy from the top part.
1191 if (Regs.size() > 1) {
1192 assert(Regs.size() == 2 &&
1193 "Cannot expand to more than 2 elts yet!");
1194 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1195 Chain = Val.getValue(1);
1196 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001197 if (DAG.getTargetLoweringInfo().isLittleEndian())
1198 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1199 else
1200 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001201 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001202
Chris Lattner6f87d182006-02-22 22:37:12 +00001203 // Otherwise, if the return value was promoted, truncate it to the
1204 // appropriate type.
1205 if (RegVT == ValueVT)
1206 return Val;
1207
1208 if (MVT::isInteger(RegVT))
1209 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1210 else
1211 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1212}
1213
Chris Lattner571d9642006-02-23 19:21:04 +00001214/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1215/// specified value into the registers specified by this object. This uses
1216/// Chain/Flag as the input and updates them for the output Chain/Flag.
1217void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001218 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001219 if (Regs.size() == 1) {
1220 // If there is a single register and the types differ, this must be
1221 // a promotion.
1222 if (RegVT != ValueVT) {
1223 if (MVT::isInteger(RegVT))
1224 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1225 else
1226 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1227 }
1228 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1229 Flag = Chain.getValue(1);
1230 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001231 std::vector<unsigned> R(Regs);
1232 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1233 std::reverse(R.begin(), R.end());
1234
1235 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001236 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1237 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001238 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001239 Flag = Chain.getValue(1);
1240 }
1241 }
1242}
Chris Lattner6f87d182006-02-22 22:37:12 +00001243
Chris Lattner571d9642006-02-23 19:21:04 +00001244/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1245/// operand list. This adds the code marker and includes the number of
1246/// values added into it.
1247void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001248 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001249 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1250 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1251 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1252}
Chris Lattner6f87d182006-02-22 22:37:12 +00001253
1254/// isAllocatableRegister - If the specified register is safe to allocate,
1255/// i.e. it isn't a stack pointer or some other special register, return the
1256/// register class for the register. Otherwise, return null.
1257static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001258isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1259 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1260 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1261 E = MRI->regclass_end(); RCI != E; ++RCI) {
1262 const TargetRegisterClass *RC = *RCI;
1263 // If none of the the value types for this register class are valid, we
1264 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1265 bool isLegal = false;
1266 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1267 I != E; ++I) {
1268 if (TLI.isTypeLegal(*I)) {
1269 isLegal = true;
1270 break;
1271 }
1272 }
1273
1274 if (!isLegal) continue;
1275
Chris Lattner6f87d182006-02-22 22:37:12 +00001276 // NOTE: This isn't ideal. In particular, this might allocate the
1277 // frame pointer in functions that need it (due to them not being taken
1278 // out of allocation, because a variable sized allocation hasn't been seen
1279 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001280 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1281 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001282 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001283 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001284 }
1285 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001286}
1287
1288RegsForValue SelectionDAGLowering::
1289GetRegistersForValue(const std::string &ConstrCode,
1290 MVT::ValueType VT, bool isOutReg, bool isInReg,
1291 std::set<unsigned> &OutputRegs,
1292 std::set<unsigned> &InputRegs) {
1293 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1294 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1295 std::vector<unsigned> Regs;
1296
1297 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1298 MVT::ValueType RegVT;
1299 MVT::ValueType ValueVT = VT;
1300
1301 if (PhysReg.first) {
1302 if (VT == MVT::Other)
1303 ValueVT = *PhysReg.second->vt_begin();
1304 RegVT = VT;
1305
1306 // This is a explicit reference to a physical register.
1307 Regs.push_back(PhysReg.first);
1308
1309 // If this is an expanded reference, add the rest of the regs to Regs.
1310 if (NumRegs != 1) {
1311 RegVT = *PhysReg.second->vt_begin();
1312 TargetRegisterClass::iterator I = PhysReg.second->begin();
1313 TargetRegisterClass::iterator E = PhysReg.second->end();
1314 for (; *I != PhysReg.first; ++I)
1315 assert(I != E && "Didn't find reg!");
1316
1317 // Already added the first reg.
1318 --NumRegs; ++I;
1319 for (; NumRegs; --NumRegs, ++I) {
1320 assert(I != E && "Ran out of registers to allocate!");
1321 Regs.push_back(*I);
1322 }
1323 }
1324 return RegsForValue(Regs, RegVT, ValueVT);
1325 }
1326
1327 // This is a reference to a register class. Allocate NumRegs consecutive,
1328 // available, registers from the class.
1329 std::vector<unsigned> RegClassRegs =
1330 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1331
1332 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1333 MachineFunction &MF = *CurMBB->getParent();
1334 unsigned NumAllocated = 0;
1335 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1336 unsigned Reg = RegClassRegs[i];
1337 // See if this register is available.
1338 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1339 (isInReg && InputRegs.count(Reg))) { // Already used.
1340 // Make sure we find consecutive registers.
1341 NumAllocated = 0;
1342 continue;
1343 }
1344
1345 // Check to see if this register is allocatable (i.e. don't give out the
1346 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001347 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001348 if (!RC) {
1349 // Make sure we find consecutive registers.
1350 NumAllocated = 0;
1351 continue;
1352 }
1353
1354 // Okay, this register is good, we can use it.
1355 ++NumAllocated;
1356
1357 // If we allocated enough consecutive
1358 if (NumAllocated == NumRegs) {
1359 unsigned RegStart = (i-NumAllocated)+1;
1360 unsigned RegEnd = i+1;
1361 // Mark all of the allocated registers used.
1362 for (unsigned i = RegStart; i != RegEnd; ++i) {
1363 unsigned Reg = RegClassRegs[i];
1364 Regs.push_back(Reg);
1365 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1366 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1367 }
1368
1369 return RegsForValue(Regs, *RC->vt_begin(), VT);
1370 }
1371 }
1372
1373 // Otherwise, we couldn't allocate enough registers for this.
1374 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001375}
1376
Chris Lattner6f87d182006-02-22 22:37:12 +00001377
Chris Lattner476e67b2006-01-26 22:24:51 +00001378/// visitInlineAsm - Handle a call to an InlineAsm object.
1379///
1380void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1381 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1382
1383 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1384 MVT::Other);
1385
1386 // Note, we treat inline asms both with and without side-effects as the same.
1387 // If an inline asm doesn't have side effects and doesn't access memory, we
1388 // could not choose to not chain it.
1389 bool hasSideEffects = IA->hasSideEffects();
1390
Chris Lattner3a5ed552006-02-01 01:28:23 +00001391 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001392 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001393
1394 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1395 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1396 /// if it is a def of that register.
1397 std::vector<SDOperand> AsmNodeOperands;
1398 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1399 AsmNodeOperands.push_back(AsmStr);
1400
1401 SDOperand Chain = getRoot();
1402 SDOperand Flag;
1403
Chris Lattner1558fc62006-02-01 18:59:47 +00001404 // We fully assign registers here at isel time. This is not optimal, but
1405 // should work. For register classes that correspond to LLVM classes, we
1406 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1407 // over the constraints, collecting fixed registers that we know we can't use.
1408 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001409 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001410 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1411 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1412 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001413
Chris Lattner7ad77df2006-02-22 00:56:39 +00001414 MVT::ValueType OpVT;
1415
1416 // Compute the value type for each operand and add it to ConstraintVTs.
1417 switch (Constraints[i].Type) {
1418 case InlineAsm::isOutput:
1419 if (!Constraints[i].isIndirectOutput) {
1420 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1421 OpVT = TLI.getValueType(I.getType());
1422 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001423 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001424 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1425 OpNum++; // Consumes a call operand.
1426 }
1427 break;
1428 case InlineAsm::isInput:
1429 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1430 OpNum++; // Consumes a call operand.
1431 break;
1432 case InlineAsm::isClobber:
1433 OpVT = MVT::Other;
1434 break;
1435 }
1436
1437 ConstraintVTs.push_back(OpVT);
1438
Chris Lattner6f87d182006-02-22 22:37:12 +00001439 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1440 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001441
Chris Lattner6f87d182006-02-22 22:37:12 +00001442 // Build a list of regs that this operand uses. This always has a single
1443 // element for promoted/expanded operands.
1444 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1445 false, false,
1446 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001447
1448 switch (Constraints[i].Type) {
1449 case InlineAsm::isOutput:
1450 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001451 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001452 // If this is an early-clobber output, it cannot be assigned to the same
1453 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001454 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001455 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001456 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001457 case InlineAsm::isInput:
1458 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001459 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001460 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001461 case InlineAsm::isClobber:
1462 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001463 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1464 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001465 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001466 }
1467 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001468
Chris Lattner5c79f982006-02-21 23:12:12 +00001469 // Loop over all of the inputs, copying the operand values into the
1470 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001471 RegsForValue RetValRegs;
1472 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001473 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001474
Chris Lattner2e56e892006-01-31 02:03:41 +00001475 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001476 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1477 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001478
Chris Lattner3a5ed552006-02-01 01:28:23 +00001479 switch (Constraints[i].Type) {
1480 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001481 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1482 if (ConstraintCode.size() == 1) // not a physreg name.
1483 CTy = TLI.getConstraintType(ConstraintCode[0]);
1484
1485 if (CTy == TargetLowering::C_Memory) {
1486 // Memory output.
1487 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1488
1489 // Check that the operand (the address to store to) isn't a float.
1490 if (!MVT::isInteger(InOperandVal.getValueType()))
1491 assert(0 && "MATCH FAIL!");
1492
1493 if (!Constraints[i].isIndirectOutput)
1494 assert(0 && "MATCH FAIL!");
1495
1496 OpNum++; // Consumes a call operand.
1497
1498 // Extend/truncate to the right pointer type if needed.
1499 MVT::ValueType PtrType = TLI.getPointerTy();
1500 if (InOperandVal.getValueType() < PtrType)
1501 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1502 else if (InOperandVal.getValueType() > PtrType)
1503 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1504
1505 // Add information to the INLINEASM node to know about this output.
1506 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1507 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1508 AsmNodeOperands.push_back(InOperandVal);
1509 break;
1510 }
1511
1512 // Otherwise, this is a register output.
1513 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1514
Chris Lattner6f87d182006-02-22 22:37:12 +00001515 // If this is an early-clobber output, or if there is an input
1516 // constraint that matches this, we need to reserve the input register
1517 // so no other inputs allocate to it.
1518 bool UsesInputRegister = false;
1519 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1520 UsesInputRegister = true;
1521
1522 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001523 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001524 RegsForValue Regs =
1525 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1526 true, UsesInputRegister,
1527 OutputRegs, InputRegs);
1528 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001529
Chris Lattner3a5ed552006-02-01 01:28:23 +00001530 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001531 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001532 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001533 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001534 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001535 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001536 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1537 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001538 OpNum++; // Consumes a call operand.
1539 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001540
1541 // Add information to the INLINEASM node to know that this register is
1542 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001543 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001544 break;
1545 }
1546 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001547 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001548 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001549
Chris Lattner7f5880b2006-02-02 00:25:23 +00001550 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1551 // If this is required to match an output register we have already set,
1552 // just use its register.
1553 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001554
Chris Lattner571d9642006-02-23 19:21:04 +00001555 // Scan until we find the definition we already emitted of this operand.
1556 // When we find it, create a RegsForValue operand.
1557 unsigned CurOp = 2; // The first operand.
1558 for (; OperandNo; --OperandNo) {
1559 // Advance to the next operand.
1560 unsigned NumOps =
1561 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1562 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1563 "Skipped past definitions?");
1564 CurOp += (NumOps>>3)+1;
1565 }
1566
1567 unsigned NumOps =
1568 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1569 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1570 "Skipped past definitions?");
1571
1572 // Add NumOps>>3 registers to MatchedRegs.
1573 RegsForValue MatchedRegs;
1574 MatchedRegs.ValueVT = InOperandVal.getValueType();
1575 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1576 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1577 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1578 MatchedRegs.Regs.push_back(Reg);
1579 }
1580
1581 // Use the produced MatchedRegs object to
1582 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1583 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001584 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001585 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001586
1587 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1588 if (ConstraintCode.size() == 1) // not a physreg name.
1589 CTy = TLI.getConstraintType(ConstraintCode[0]);
1590
1591 if (CTy == TargetLowering::C_Other) {
1592 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1593 assert(0 && "MATCH FAIL!");
1594
1595 // Add information to the INLINEASM node to know about this input.
1596 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1597 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1598 AsmNodeOperands.push_back(InOperandVal);
1599 break;
1600 } else if (CTy == TargetLowering::C_Memory) {
1601 // Memory input.
1602
1603 // Check that the operand isn't a float.
1604 if (!MVT::isInteger(InOperandVal.getValueType()))
1605 assert(0 && "MATCH FAIL!");
1606
1607 // Extend/truncate to the right pointer type if needed.
1608 MVT::ValueType PtrType = TLI.getPointerTy();
1609 if (InOperandVal.getValueType() < PtrType)
1610 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1611 else if (InOperandVal.getValueType() > PtrType)
1612 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1613
1614 // Add information to the INLINEASM node to know about this input.
1615 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1616 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1617 AsmNodeOperands.push_back(InOperandVal);
1618 break;
1619 }
1620
1621 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1622
1623 // Copy the input into the appropriate registers.
1624 RegsForValue InRegs =
1625 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1626 false, true, OutputRegs, InputRegs);
1627 // FIXME: should be match fail.
1628 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1629
1630 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1631
1632 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001633 break;
1634 }
Chris Lattner571d9642006-02-23 19:21:04 +00001635 case InlineAsm::isClobber: {
1636 RegsForValue ClobberedRegs =
1637 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1638 OutputRegs, InputRegs);
1639 // Add the clobbered value to the operand list, so that the register
1640 // allocator is aware that the physreg got clobbered.
1641 if (!ClobberedRegs.Regs.empty())
1642 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001643 break;
1644 }
Chris Lattner571d9642006-02-23 19:21:04 +00001645 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001646 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001647
1648 // Finish up input operands.
1649 AsmNodeOperands[0] = Chain;
1650 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1651
1652 std::vector<MVT::ValueType> VTs;
1653 VTs.push_back(MVT::Other);
1654 VTs.push_back(MVT::Flag);
1655 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1656 Flag = Chain.getValue(1);
1657
Chris Lattner2e56e892006-01-31 02:03:41 +00001658 // If this asm returns a register value, copy the result from that register
1659 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001660 if (!RetValRegs.Regs.empty())
1661 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001662
Chris Lattner2e56e892006-01-31 02:03:41 +00001663 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1664
1665 // Process indirect outputs, first output all of the flagged copies out of
1666 // physregs.
1667 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001668 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001669 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001670 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1671 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001672 }
1673
1674 // Emit the non-flagged stores from the physregs.
1675 std::vector<SDOperand> OutChains;
1676 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1677 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1678 StoresToEmit[i].first,
1679 getValue(StoresToEmit[i].second),
1680 DAG.getSrcValue(StoresToEmit[i].second)));
1681 if (!OutChains.empty())
1682 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001683 DAG.setRoot(Chain);
1684}
1685
1686
Chris Lattner7a60d912005-01-07 07:47:53 +00001687void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1688 SDOperand Src = getValue(I.getOperand(0));
1689
1690 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001691
1692 if (IntPtr < Src.getValueType())
1693 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1694 else if (IntPtr > Src.getValueType())
1695 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001696
1697 // Scale the source by the type size.
1698 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1699 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1700 Src, getIntPtrConstant(ElementSize));
1701
1702 std::vector<std::pair<SDOperand, const Type*> > Args;
1703 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001704
1705 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001706 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001707 DAG.getExternalSymbol("malloc", IntPtr),
1708 Args, DAG);
1709 setValue(&I, Result.first); // Pointers always fit in registers
1710 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001711}
1712
1713void SelectionDAGLowering::visitFree(FreeInst &I) {
1714 std::vector<std::pair<SDOperand, const Type*> > Args;
1715 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1716 TLI.getTargetData().getIntPtrType()));
1717 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001718 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001719 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001720 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1721 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001722}
1723
Chris Lattner13d7c252005-08-26 20:54:47 +00001724// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1725// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1726// instructions are special in various ways, which require special support to
1727// insert. The specified MachineInstr is created but not inserted into any
1728// basic blocks, and the scheduler passes ownership of it to this method.
1729MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1730 MachineBasicBlock *MBB) {
1731 std::cerr << "If a target marks an instruction with "
1732 "'usesCustomDAGSchedInserter', it must implement "
1733 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1734 abort();
1735 return 0;
1736}
1737
Chris Lattner58cfd792005-01-09 00:00:49 +00001738void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001739 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1740 getValue(I.getOperand(1)),
1741 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001742}
1743
1744void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001745 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1746 getValue(I.getOperand(0)),
1747 DAG.getSrcValue(I.getOperand(0)));
1748 setValue(&I, V);
1749 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001750}
1751
1752void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001753 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1754 getValue(I.getOperand(1)),
1755 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001756}
1757
1758void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001759 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1760 getValue(I.getOperand(1)),
1761 getValue(I.getOperand(2)),
1762 DAG.getSrcValue(I.getOperand(1)),
1763 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001764}
1765
Chris Lattner58cfd792005-01-09 00:00:49 +00001766// It is always conservatively correct for llvm.returnaddress and
1767// llvm.frameaddress to return 0.
1768std::pair<SDOperand, SDOperand>
1769TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1770 unsigned Depth, SelectionDAG &DAG) {
1771 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001772}
1773
Chris Lattner29dcc712005-05-14 05:50:48 +00001774SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001775 assert(0 && "LowerOperation not implemented for this target!");
1776 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001777 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001778}
1779
Nate Begeman595ec732006-01-28 03:14:31 +00001780SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1781 SelectionDAG &DAG) {
1782 assert(0 && "CustomPromoteOperation not implemented for this target!");
1783 abort();
1784 return SDOperand();
1785}
1786
Chris Lattner58cfd792005-01-09 00:00:49 +00001787void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1788 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1789 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001790 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001791 setValue(&I, Result.first);
1792 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001793}
1794
Evan Cheng6781b6e2006-02-15 21:59:04 +00001795/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001796/// operand.
1797static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001798 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001799 MVT::ValueType CurVT = VT;
1800 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1801 uint64_t Val = C->getValue() & 255;
1802 unsigned Shift = 8;
1803 while (CurVT != MVT::i8) {
1804 Val = (Val << Shift) | Val;
1805 Shift <<= 1;
1806 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001807 }
1808 return DAG.getConstant(Val, VT);
1809 } else {
1810 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1811 unsigned Shift = 8;
1812 while (CurVT != MVT::i8) {
1813 Value =
1814 DAG.getNode(ISD::OR, VT,
1815 DAG.getNode(ISD::SHL, VT, Value,
1816 DAG.getConstant(Shift, MVT::i8)), Value);
1817 Shift <<= 1;
1818 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001819 }
1820
1821 return Value;
1822 }
1823}
1824
Evan Cheng6781b6e2006-02-15 21:59:04 +00001825/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1826/// used when a memcpy is turned into a memset when the source is a constant
1827/// string ptr.
1828static SDOperand getMemsetStringVal(MVT::ValueType VT,
1829 SelectionDAG &DAG, TargetLowering &TLI,
1830 std::string &Str, unsigned Offset) {
1831 MVT::ValueType CurVT = VT;
1832 uint64_t Val = 0;
1833 unsigned MSB = getSizeInBits(VT) / 8;
1834 if (TLI.isLittleEndian())
1835 Offset = Offset + MSB - 1;
1836 for (unsigned i = 0; i != MSB; ++i) {
1837 Val = (Val << 8) | Str[Offset];
1838 Offset += TLI.isLittleEndian() ? -1 : 1;
1839 }
1840 return DAG.getConstant(Val, VT);
1841}
1842
Evan Cheng81fcea82006-02-14 08:22:34 +00001843/// getMemBasePlusOffset - Returns base and offset node for the
1844static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1845 SelectionDAG &DAG, TargetLowering &TLI) {
1846 MVT::ValueType VT = Base.getValueType();
1847 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1848}
1849
Evan Chengdb2a7a72006-02-14 20:12:38 +00001850/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001851/// to replace the memset / memcpy is below the threshold. It also returns the
1852/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001853static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1854 unsigned Limit, uint64_t Size,
1855 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001856 MVT::ValueType VT;
1857
1858 if (TLI.allowsUnalignedMemoryAccesses()) {
1859 VT = MVT::i64;
1860 } else {
1861 switch (Align & 7) {
1862 case 0:
1863 VT = MVT::i64;
1864 break;
1865 case 4:
1866 VT = MVT::i32;
1867 break;
1868 case 2:
1869 VT = MVT::i16;
1870 break;
1871 default:
1872 VT = MVT::i8;
1873 break;
1874 }
1875 }
1876
Evan Chengd5026102006-02-14 09:11:59 +00001877 MVT::ValueType LVT = MVT::i64;
1878 while (!TLI.isTypeLegal(LVT))
1879 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1880 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001881
Evan Chengd5026102006-02-14 09:11:59 +00001882 if (VT > LVT)
1883 VT = LVT;
1884
Evan Cheng04514992006-02-14 23:05:54 +00001885 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001886 while (Size != 0) {
1887 unsigned VTSize = getSizeInBits(VT) / 8;
1888 while (VTSize > Size) {
1889 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001890 VTSize >>= 1;
1891 }
Evan Chengd5026102006-02-14 09:11:59 +00001892 assert(MVT::isInteger(VT));
1893
1894 if (++NumMemOps > Limit)
1895 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001896 MemOps.push_back(VT);
1897 Size -= VTSize;
1898 }
Evan Chengd5026102006-02-14 09:11:59 +00001899
1900 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001901}
1902
Chris Lattner875def92005-01-11 05:56:49 +00001903void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001904 SDOperand Op1 = getValue(I.getOperand(1));
1905 SDOperand Op2 = getValue(I.getOperand(2));
1906 SDOperand Op3 = getValue(I.getOperand(3));
1907 SDOperand Op4 = getValue(I.getOperand(4));
1908 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1909 if (Align == 0) Align = 1;
1910
1911 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1912 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001913
1914 // Expand memset / memcpy to a series of load / store ops
1915 // if the size operand falls below a certain threshold.
1916 std::vector<SDOperand> OutChains;
1917 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00001918 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00001919 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00001920 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1921 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00001922 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00001923 unsigned Offset = 0;
1924 for (unsigned i = 0; i < NumMemOps; i++) {
1925 MVT::ValueType VT = MemOps[i];
1926 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00001927 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00001928 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1929 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00001930 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1931 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00001932 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00001933 Offset += VTSize;
1934 }
Evan Cheng81fcea82006-02-14 08:22:34 +00001935 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001936 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00001937 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001938 case ISD::MEMCPY: {
1939 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1940 Size->getValue(), Align, TLI)) {
1941 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001942 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001943 GlobalAddressSDNode *G = NULL;
1944 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001945 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001946
1947 if (Op2.getOpcode() == ISD::GlobalAddress)
1948 G = cast<GlobalAddressSDNode>(Op2);
1949 else if (Op2.getOpcode() == ISD::ADD &&
1950 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1951 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1952 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001953 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00001954 }
1955 if (G) {
1956 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001957 if (GV) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00001958 Str = getStringValue(GV);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001959 if (!Str.empty()) {
1960 CopyFromStr = true;
1961 SrcOff += SrcDelta;
1962 }
1963 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00001964 }
1965
Evan Chenge2038bd2006-02-15 01:54:51 +00001966 for (unsigned i = 0; i < NumMemOps; i++) {
1967 MVT::ValueType VT = MemOps[i];
1968 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001969 SDOperand Value, Chain, Store;
1970
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001971 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00001972 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1973 Chain = getRoot();
1974 Store =
1975 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1976 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1977 DAG.getSrcValue(I.getOperand(1), DstOff));
1978 } else {
1979 Value = DAG.getLoad(VT, getRoot(),
1980 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1981 DAG.getSrcValue(I.getOperand(2), SrcOff));
1982 Chain = Value.getValue(1);
1983 Store =
1984 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1985 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1986 DAG.getSrcValue(I.getOperand(1), DstOff));
1987 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001988 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00001989 SrcOff += VTSize;
1990 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00001991 }
1992 }
1993 break;
1994 }
1995 }
1996
1997 if (!OutChains.empty()) {
1998 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
1999 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002000 }
2001 }
2002
Chris Lattner875def92005-01-11 05:56:49 +00002003 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002004 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002005 Ops.push_back(Op1);
2006 Ops.push_back(Op2);
2007 Ops.push_back(Op3);
2008 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002009 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002010}
2011
Chris Lattner875def92005-01-11 05:56:49 +00002012//===----------------------------------------------------------------------===//
2013// SelectionDAGISel code
2014//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002015
2016unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2017 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2018}
2019
Chris Lattnerc9950c12005-08-17 06:37:43 +00002020void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002021 // FIXME: we only modify the CFG to split critical edges. This
2022 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002023}
Chris Lattner7a60d912005-01-07 07:47:53 +00002024
Chris Lattner35397782005-12-05 07:10:48 +00002025
2026/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2027/// casting to the type of GEPI.
2028static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2029 Value *Ptr, Value *PtrOffset) {
2030 if (V) return V; // Already computed.
2031
2032 BasicBlock::iterator InsertPt;
2033 if (BB == GEPI->getParent()) {
2034 // If insert into the GEP's block, insert right after the GEP.
2035 InsertPt = GEPI;
2036 ++InsertPt;
2037 } else {
2038 // Otherwise, insert at the top of BB, after any PHI nodes
2039 InsertPt = BB->begin();
2040 while (isa<PHINode>(InsertPt)) ++InsertPt;
2041 }
2042
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002043 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2044 // BB so that there is only one value live across basic blocks (the cast
2045 // operand).
2046 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2047 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2048 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2049
Chris Lattner35397782005-12-05 07:10:48 +00002050 // Add the offset, cast it to the right type.
2051 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2052 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2053 return V = Ptr;
2054}
2055
2056
2057/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2058/// selection, we want to be a bit careful about some things. In particular, if
2059/// we have a GEP instruction that is used in a different block than it is
2060/// defined, the addressing expression of the GEP cannot be folded into loads or
2061/// stores that use it. In this case, decompose the GEP and move constant
2062/// indices into blocks that use it.
2063static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2064 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002065 // If this GEP is only used inside the block it is defined in, there is no
2066 // need to rewrite it.
2067 bool isUsedOutsideDefBB = false;
2068 BasicBlock *DefBB = GEPI->getParent();
2069 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2070 UI != E; ++UI) {
2071 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2072 isUsedOutsideDefBB = true;
2073 break;
2074 }
2075 }
2076 if (!isUsedOutsideDefBB) return;
2077
2078 // If this GEP has no non-zero constant indices, there is nothing we can do,
2079 // ignore it.
2080 bool hasConstantIndex = false;
2081 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2082 E = GEPI->op_end(); OI != E; ++OI) {
2083 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2084 if (CI->getRawValue()) {
2085 hasConstantIndex = true;
2086 break;
2087 }
2088 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002089 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2090 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002091
2092 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2093 // constant offset (which we now know is non-zero) and deal with it later.
2094 uint64_t ConstantOffset = 0;
2095 const Type *UIntPtrTy = TD.getIntPtrType();
2096 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2097 const Type *Ty = GEPI->getOperand(0)->getType();
2098
2099 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2100 E = GEPI->op_end(); OI != E; ++OI) {
2101 Value *Idx = *OI;
2102 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2103 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2104 if (Field)
2105 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2106 Ty = StTy->getElementType(Field);
2107 } else {
2108 Ty = cast<SequentialType>(Ty)->getElementType();
2109
2110 // Handle constant subscripts.
2111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2112 if (CI->getRawValue() == 0) continue;
2113
2114 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2115 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2116 else
2117 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2118 continue;
2119 }
2120
2121 // Ptr = Ptr + Idx * ElementSize;
2122
2123 // Cast Idx to UIntPtrTy if needed.
2124 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2125
2126 uint64_t ElementSize = TD.getTypeSize(Ty);
2127 // Mask off bits that should not be set.
2128 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2129 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2130
2131 // Multiply by the element size and add to the base.
2132 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2133 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2134 }
2135 }
2136
2137 // Make sure that the offset fits in uintptr_t.
2138 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2139 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2140
2141 // Okay, we have now emitted all of the variable index parts to the BB that
2142 // the GEP is defined in. Loop over all of the using instructions, inserting
2143 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002144 // instruction to use the newly computed value, making GEPI dead. When the
2145 // user is a load or store instruction address, we emit the add into the user
2146 // block, otherwise we use a canonical version right next to the gep (these
2147 // won't be foldable as addresses, so we might as well share the computation).
2148
Chris Lattner35397782005-12-05 07:10:48 +00002149 std::map<BasicBlock*,Value*> InsertedExprs;
2150 while (!GEPI->use_empty()) {
2151 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002152
2153 // If this use is not foldable into the addressing mode, use a version
2154 // emitted in the GEP block.
2155 Value *NewVal;
2156 if (!isa<LoadInst>(User) &&
2157 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2158 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2159 Ptr, PtrOffset);
2160 } else {
2161 // Otherwise, insert the code in the User's block so it can be folded into
2162 // any users in that block.
2163 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002164 User->getParent(), GEPI,
2165 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002166 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002167 User->replaceUsesOfWith(GEPI, NewVal);
2168 }
Chris Lattner35397782005-12-05 07:10:48 +00002169
2170 // Finally, the GEP is dead, remove it.
2171 GEPI->eraseFromParent();
2172}
2173
Chris Lattner7a60d912005-01-07 07:47:53 +00002174bool SelectionDAGISel::runOnFunction(Function &Fn) {
2175 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2176 RegMap = MF.getSSARegMap();
2177 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2178
Chris Lattner35397782005-12-05 07:10:48 +00002179 // First, split all critical edges for PHI nodes with incoming values that are
2180 // constants, this way the load of the constant into a vreg will not be placed
2181 // into MBBs that are used some other way.
2182 //
2183 // In this pass we also look for GEP instructions that are used across basic
2184 // blocks and rewrites them to improve basic-block-at-a-time selection.
2185 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002186 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2187 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002188 BasicBlock::iterator BBI;
2189 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002190 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2191 if (isa<Constant>(PN->getIncomingValue(i)))
2192 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002193
2194 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2195 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2196 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002197 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002198
Chris Lattner7a60d912005-01-07 07:47:53 +00002199 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2200
2201 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2202 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002203
Chris Lattner7a60d912005-01-07 07:47:53 +00002204 return true;
2205}
2206
2207
Chris Lattner718b5c22005-01-13 17:59:43 +00002208SDOperand SelectionDAGISel::
2209CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002210 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002211 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002212 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002213 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002214
2215 // If this type is not legal, we must make sure to not create an invalid
2216 // register use.
2217 MVT::ValueType SrcVT = Op.getValueType();
2218 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2219 SelectionDAG &DAG = SDL.DAG;
2220 if (SrcVT == DestVT) {
2221 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2222 } else if (SrcVT < DestVT) {
2223 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002224 if (MVT::isFloatingPoint(SrcVT))
2225 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2226 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002227 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002228 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2229 } else {
2230 // The src value is expanded into multiple registers.
2231 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2232 Op, DAG.getConstant(0, MVT::i32));
2233 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2234 Op, DAG.getConstant(1, MVT::i32));
2235 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2236 return DAG.getCopyToReg(Op, Reg+1, Hi);
2237 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002238}
2239
Chris Lattner16f64df2005-01-17 17:15:02 +00002240void SelectionDAGISel::
2241LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2242 std::vector<SDOperand> &UnorderedChains) {
2243 // If this is the entry block, emit arguments.
2244 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002245 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002246 SDOperand OldRoot = SDL.DAG.getRoot();
2247 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002248
Chris Lattner6871b232005-10-30 19:42:35 +00002249 unsigned a = 0;
2250 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2251 AI != E; ++AI, ++a)
2252 if (!AI->use_empty()) {
2253 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002254
Chris Lattner6871b232005-10-30 19:42:35 +00002255 // If this argument is live outside of the entry block, insert a copy from
2256 // whereever we got it to the vreg that other BB's will reference it as.
2257 if (FuncInfo.ValueMap.count(AI)) {
2258 SDOperand Copy =
2259 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2260 UnorderedChains.push_back(Copy);
2261 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002262 }
Chris Lattner6871b232005-10-30 19:42:35 +00002263
2264 // Next, if the function has live ins that need to be copied into vregs,
2265 // emit the copies now, into the top of the block.
2266 MachineFunction &MF = SDL.DAG.getMachineFunction();
2267 if (MF.livein_begin() != MF.livein_end()) {
2268 SSARegMap *RegMap = MF.getSSARegMap();
2269 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2270 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2271 E = MF.livein_end(); LI != E; ++LI)
2272 if (LI->second)
2273 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2274 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002275 }
Chris Lattner6871b232005-10-30 19:42:35 +00002276
2277 // Finally, if the target has anything special to do, allow it to do so.
2278 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002279}
2280
2281
Chris Lattner7a60d912005-01-07 07:47:53 +00002282void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2283 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2284 FunctionLoweringInfo &FuncInfo) {
2285 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002286
2287 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002288
Chris Lattner6871b232005-10-30 19:42:35 +00002289 // Lower any arguments needed in this block if this is the entry block.
2290 if (LLVMBB == &LLVMBB->getParent()->front())
2291 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002292
2293 BB = FuncInfo.MBBMap[LLVMBB];
2294 SDL.setCurrentBasicBlock(BB);
2295
2296 // Lower all of the non-terminator instructions.
2297 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2298 I != E; ++I)
2299 SDL.visit(*I);
2300
2301 // Ensure that all instructions which are used outside of their defining
2302 // blocks are available as virtual registers.
2303 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002304 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002305 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002306 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002307 UnorderedChains.push_back(
2308 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002309 }
2310
2311 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2312 // ensure constants are generated when needed. Remember the virtual registers
2313 // that need to be added to the Machine PHI nodes as input. We cannot just
2314 // directly add them, because expansion might result in multiple MBB's for one
2315 // BB. As such, the start of the BB might correspond to a different MBB than
2316 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002317 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002318
2319 // Emit constants only once even if used by multiple PHI nodes.
2320 std::map<Constant*, unsigned> ConstantsOut;
2321
2322 // Check successor nodes PHI nodes that expect a constant to be available from
2323 // this block.
2324 TerminatorInst *TI = LLVMBB->getTerminator();
2325 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2326 BasicBlock *SuccBB = TI->getSuccessor(succ);
2327 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2328 PHINode *PN;
2329
2330 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2331 // nodes and Machine PHI nodes, but the incoming operands have not been
2332 // emitted yet.
2333 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002334 (PN = dyn_cast<PHINode>(I)); ++I)
2335 if (!PN->use_empty()) {
2336 unsigned Reg;
2337 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2338 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2339 unsigned &RegOut = ConstantsOut[C];
2340 if (RegOut == 0) {
2341 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002342 UnorderedChains.push_back(
2343 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002344 }
2345 Reg = RegOut;
2346 } else {
2347 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002348 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002349 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002350 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2351 "Didn't codegen value into a register!??");
2352 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002353 UnorderedChains.push_back(
2354 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002355 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002356 }
Misha Brukman835702a2005-04-21 22:36:52 +00002357
Chris Lattner8ea875f2005-01-07 21:34:19 +00002358 // Remember that this register needs to added to the machine PHI node as
2359 // the input for this MBB.
2360 unsigned NumElements =
2361 TLI.getNumElements(TLI.getValueType(PN->getType()));
2362 for (unsigned i = 0, e = NumElements; i != e; ++i)
2363 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002364 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002365 }
2366 ConstantsOut.clear();
2367
Chris Lattner718b5c22005-01-13 17:59:43 +00002368 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002369 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002370 SDOperand Root = SDL.getRoot();
2371 if (Root.getOpcode() != ISD::EntryToken) {
2372 unsigned i = 0, e = UnorderedChains.size();
2373 for (; i != e; ++i) {
2374 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2375 if (UnorderedChains[i].Val->getOperand(0) == Root)
2376 break; // Don't add the root if we already indirectly depend on it.
2377 }
2378
2379 if (i == e)
2380 UnorderedChains.push_back(Root);
2381 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002382 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2383 }
2384
Chris Lattner7a60d912005-01-07 07:47:53 +00002385 // Lower the terminator after the copies are emitted.
2386 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002387
2388 // Make sure the root of the DAG is up-to-date.
2389 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002390}
2391
2392void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2393 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002394 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002395 CurDAG = &DAG;
2396 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2397
2398 // First step, lower LLVM code to some DAG. This DAG may use operations and
2399 // types that are not supported by the target.
2400 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2401
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002402 // Run the DAG combiner in pre-legalize mode.
2403 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002404
Chris Lattner7a60d912005-01-07 07:47:53 +00002405 DEBUG(std::cerr << "Lowered selection DAG:\n");
2406 DEBUG(DAG.dump());
2407
2408 // Second step, hack on the DAG until it only uses operations and types that
2409 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002410 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002411
2412 DEBUG(std::cerr << "Legalized selection DAG:\n");
2413 DEBUG(DAG.dump());
2414
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002415 // Run the DAG combiner in post-legalize mode.
2416 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002417
Evan Cheng739a6a42006-01-21 02:32:06 +00002418 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002419
Chris Lattner5ca31d92005-03-30 01:10:47 +00002420 // Third, instruction select all of the operations to machine code, adding the
2421 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002422 InstructionSelectBasicBlock(DAG);
2423
Chris Lattner7a60d912005-01-07 07:47:53 +00002424 DEBUG(std::cerr << "Selected machine code:\n");
2425 DEBUG(BB->dump());
2426
Chris Lattner5ca31d92005-03-30 01:10:47 +00002427 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002428 // PHI nodes in successors.
2429 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2430 MachineInstr *PHI = PHINodesToUpdate[i].first;
2431 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2432 "This is not a machine PHI node that we are updating!");
2433 PHI->addRegOperand(PHINodesToUpdate[i].second);
2434 PHI->addMachineBasicBlockOperand(BB);
2435 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002436
2437 // Finally, add the CFG edges from the last selected MBB to the successor
2438 // MBBs.
2439 TerminatorInst *TI = LLVMBB->getTerminator();
2440 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2441 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2442 BB->addSuccessor(Succ0MBB);
2443 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002444}
Evan Cheng739a6a42006-01-21 02:32:06 +00002445
2446//===----------------------------------------------------------------------===//
2447/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2448/// target node in the graph.
2449void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2450 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002451 ScheduleDAG *SL = NULL;
2452
2453 switch (ISHeuristic) {
2454 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002455 case defaultScheduling:
2456 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2457 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2458 else /* TargetLowering::SchedulingForRegPressure */
2459 SL = createBURRListDAGScheduler(DAG, BB);
2460 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002461 case noScheduling:
2462 case simpleScheduling:
2463 case simpleNoItinScheduling:
2464 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
2465 break;
Evan Cheng31272342006-01-23 08:26:10 +00002466 case listSchedulingBURR:
2467 SL = createBURRListDAGScheduler(DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002468 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002469 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002470 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002471}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002472
2473/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2474/// by tblgen. Others should not call it.
2475void SelectionDAGISel::
2476SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2477 std::vector<SDOperand> InOps;
2478 std::swap(InOps, Ops);
2479
2480 Ops.push_back(InOps[0]); // input chain.
2481 Ops.push_back(InOps[1]); // input asm string.
2482
2483 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2484 unsigned i = 2, e = InOps.size();
2485 if (InOps[e-1].getValueType() == MVT::Flag)
2486 --e; // Don't process a flag operand if it is here.
2487
2488 while (i != e) {
2489 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2490 if ((Flags & 7) != 4 /*MEM*/) {
2491 // Just skip over this operand, copying the operands verbatim.
2492 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2493 i += (Flags >> 3) + 1;
2494 } else {
2495 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2496 // Otherwise, this is a memory operand. Ask the target to select it.
2497 std::vector<SDOperand> SelOps;
2498 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2499 std::cerr << "Could not match memory address. Inline asm failure!\n";
2500 exit(1);
2501 }
2502
2503 // Add this to the output node.
2504 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2505 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2506 i += 2;
2507 }
2508 }
2509
2510 // Add the flag input back if present.
2511 if (e != InOps.size())
2512 Ops.push_back(InOps.back());
2513}