blob: 2028332f2f1f843a25fe11b27107f354da926d38 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-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 Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-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 Chenga9c20912006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-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 Lattnerfa577022005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-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 Lattner495a0b52005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner4e4b5762006-02-01 18:59:47 +000043#include <set>
Chris Lattner1c08c712005-01-07 07:47:53 +000044#include <iostream>
45using namespace llvm;
46
Chris Lattnerda8abb02005-09-01 18:44:10 +000047#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000048static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000049ViewISelDAGs("view-isel-dags", cl::Hidden,
50 cl::desc("Pop up a window to show isel dags as they are selected"));
51static cl::opt<bool>
52ViewSchedDAGs("view-sched-dags", cl::Hidden,
53 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000054#else
Evan Chenga9c20912006-01-21 02:32:06 +000055static const bool ViewISelDAGs = 0;
56static const bool ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000057#endif
58
Evan Cheng4ef10862006-01-23 07:01:07 +000059namespace {
60 cl::opt<SchedHeuristics>
61 ISHeuristic(
62 "sched",
63 cl::desc("Choose scheduling style"),
Evan Cheng3f239522006-01-25 09:12:57 +000064 cl::init(defaultScheduling),
Evan Cheng4ef10862006-01-23 07:01:07 +000065 cl::values(
Evan Cheng3f239522006-01-25 09:12:57 +000066 clEnumValN(defaultScheduling, "default",
67 "Target preferred scheduling style"),
Evan Cheng4ef10862006-01-23 07:01:07 +000068 clEnumValN(noScheduling, "none",
Jim Laskey17d52f72006-01-23 13:34:04 +000069 "No scheduling: breadth first sequencing"),
Evan Cheng4ef10862006-01-23 07:01:07 +000070 clEnumValN(simpleScheduling, "simple",
71 "Simple two pass scheduling: minimize critical path "
72 "and maximize processor utilization"),
73 clEnumValN(simpleNoItinScheduling, "simple-noitin",
74 "Simple two pass scheduling: Same as simple "
75 "except using generic latency"),
Evan Cheng3f239522006-01-25 09:12:57 +000076 clEnumValN(listSchedulingBURR, "list-burr",
Evan Chengf0f9c902006-01-23 08:26:10 +000077 "Bottom up register reduction list scheduling"),
Evan Cheng4ef10862006-01-23 07:01:07 +000078 clEnumValEnd));
79} // namespace
80
Chris Lattner864635a2006-02-22 22:37:12 +000081namespace {
82 /// RegsForValue - This struct represents the physical registers that a
83 /// particular value is assigned and the type information about the value.
84 /// This is needed because values can be promoted into larger registers and
85 /// expanded into multiple smaller registers than the value.
86 struct RegsForValue {
87 /// Regs - This list hold the register (for legal and promoted values)
88 /// or register set (for expanded values) that the value should be assigned
89 /// to.
90 std::vector<unsigned> Regs;
91
92 /// RegVT - The value type of each register.
93 ///
94 MVT::ValueType RegVT;
95
96 /// ValueVT - The value type of the LLVM value, which may be promoted from
97 /// RegVT or made from merging the two expanded parts.
98 MVT::ValueType ValueVT;
99
100 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
101
102 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
103 : RegVT(regvt), ValueVT(valuevt) {
104 Regs.push_back(Reg);
105 }
106 RegsForValue(const std::vector<unsigned> &regs,
107 MVT::ValueType regvt, MVT::ValueType valuevt)
108 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
109 }
110
111 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
112 /// this value and returns the result as a ValueVT value. This uses
113 /// Chain/Flag as the input and updates them for the output Chain/Flag.
114 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000115 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000116
117 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
118 /// specified value into the registers specified by this object. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000121 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000122
123 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
124 /// operand list. This adds the code marker and includes the number of
125 /// values added into it.
126 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000127 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000128 };
129}
Evan Cheng4ef10862006-01-23 07:01:07 +0000130
Chris Lattner1c08c712005-01-07 07:47:53 +0000131namespace llvm {
132 //===--------------------------------------------------------------------===//
133 /// FunctionLoweringInfo - This contains information that is global to a
134 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000135 class FunctionLoweringInfo {
136 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000137 TargetLowering &TLI;
138 Function &Fn;
139 MachineFunction &MF;
140 SSARegMap *RegMap;
141
142 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
143
144 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
145 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
146
147 /// ValueMap - Since we emit code for the function a basic block at a time,
148 /// we must remember which virtual registers hold the values for
149 /// cross-basic-block values.
150 std::map<const Value*, unsigned> ValueMap;
151
152 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
153 /// the entry block. This allows the allocas to be efficiently referenced
154 /// anywhere in the function.
155 std::map<const AllocaInst*, int> StaticAllocaMap;
156
157 unsigned MakeReg(MVT::ValueType VT) {
158 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
159 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000160
Chris Lattner1c08c712005-01-07 07:47:53 +0000161 unsigned CreateRegForValue(const Value *V) {
162 MVT::ValueType VT = TLI.getValueType(V->getType());
163 // The common case is that we will only create one register for this
164 // value. If we have that case, create and return the virtual register.
165 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +0000166 if (NV == 1) {
167 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +0000168 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +0000169 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000170
Chris Lattner1c08c712005-01-07 07:47:53 +0000171 // If this value is represented with multiple target registers, make sure
Chris Lattner864635a2006-02-22 22:37:12 +0000172 // to create enough consecutive registers of the right (smaller) type.
Chris Lattner1c08c712005-01-07 07:47:53 +0000173 unsigned NT = VT-1; // Find the type to use.
174 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
175 --NT;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000176
Chris Lattner1c08c712005-01-07 07:47:53 +0000177 unsigned R = MakeReg((MVT::ValueType)NT);
178 for (unsigned i = 1; i != NV; ++i)
179 MakeReg((MVT::ValueType)NT);
180 return R;
181 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000182
Chris Lattner1c08c712005-01-07 07:47:53 +0000183 unsigned InitializeRegForValue(const Value *V) {
184 unsigned &R = ValueMap[V];
185 assert(R == 0 && "Already initialized this value register!");
186 return R = CreateRegForValue(V);
187 }
188 };
189}
190
191/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
192/// PHI nodes or outside of the basic block that defines it.
193static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
194 if (isa<PHINode>(I)) return true;
195 BasicBlock *BB = I->getParent();
196 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
197 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
198 return true;
199 return false;
200}
201
Chris Lattnerbf209482005-10-30 19:42:35 +0000202/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
203/// entry block, return true.
204static bool isOnlyUsedInEntryBlock(Argument *A) {
205 BasicBlock *Entry = A->getParent()->begin();
206 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
207 if (cast<Instruction>(*UI)->getParent() != Entry)
208 return false; // Use not in entry block.
209 return true;
210}
211
Chris Lattner1c08c712005-01-07 07:47:53 +0000212FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000213 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000214 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
215
Chris Lattnerbf209482005-10-30 19:42:35 +0000216 // Create a vreg for each argument register that is not dead and is used
217 // outside of the entry block for the function.
218 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
219 AI != E; ++AI)
220 if (!isOnlyUsedInEntryBlock(AI))
221 InitializeRegForValue(AI);
222
Chris Lattner1c08c712005-01-07 07:47:53 +0000223 // Initialize the mapping of values to registers. This is only set up for
224 // instruction values that are used outside of the block that defines
225 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000226 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000227 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
228 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
229 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
230 const Type *Ty = AI->getAllocatedType();
231 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000232 unsigned Align =
233 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
234 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000235
236 // If the alignment of the value is smaller than the size of the value,
237 // and if the size of the value is particularly small (<= 8 bytes),
238 // round up to the size of the value for potentially better performance.
239 //
240 // FIXME: This could be made better with a preferred alignment hook in
241 // TargetData. It serves primarily to 8-byte align doubles for X86.
242 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000243 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000244 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000245 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000246 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000247 }
248
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000249 for (; BB != EB; ++BB)
250 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000251 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
252 if (!isa<AllocaInst>(I) ||
253 !StaticAllocaMap.count(cast<AllocaInst>(I)))
254 InitializeRegForValue(I);
255
256 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
257 // also creates the initial PHI MachineInstrs, though none of the input
258 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000259 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000260 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
261 MBBMap[BB] = MBB;
262 MF.getBasicBlockList().push_back(MBB);
263
264 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
265 // appropriate.
266 PHINode *PN;
267 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000268 (PN = dyn_cast<PHINode>(I)); ++I)
269 if (!PN->use_empty()) {
270 unsigned NumElements =
271 TLI.getNumElements(TLI.getValueType(PN->getType()));
272 unsigned PHIReg = ValueMap[PN];
273 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
274 for (unsigned i = 0; i != NumElements; ++i)
275 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
276 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000277 }
278}
279
280
281
282//===----------------------------------------------------------------------===//
283/// SelectionDAGLowering - This is the common target-independent lowering
284/// implementation that is parameterized by a TargetLowering object.
285/// Also, targets can overload any lowering method.
286///
287namespace llvm {
288class SelectionDAGLowering {
289 MachineBasicBlock *CurMBB;
290
291 std::map<const Value*, SDOperand> NodeMap;
292
Chris Lattnerd3948112005-01-17 22:19:26 +0000293 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
294 /// them up and then emit token factor nodes when possible. This allows us to
295 /// get simple disambiguation between loads without worrying about alias
296 /// analysis.
297 std::vector<SDOperand> PendingLoads;
298
Chris Lattner1c08c712005-01-07 07:47:53 +0000299public:
300 // TLI - This is information that describes the available target features we
301 // need for lowering. This indicates when operations are unavailable,
302 // implemented with a libcall, etc.
303 TargetLowering &TLI;
304 SelectionDAG &DAG;
305 const TargetData &TD;
306
307 /// FuncInfo - Information about the function as a whole.
308 ///
309 FunctionLoweringInfo &FuncInfo;
310
311 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000312 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000313 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
314 FuncInfo(funcinfo) {
315 }
316
Chris Lattnera651cf62005-01-17 19:43:36 +0000317 /// getRoot - Return the current virtual root of the Selection DAG.
318 ///
319 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000320 if (PendingLoads.empty())
321 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000322
Chris Lattnerd3948112005-01-17 22:19:26 +0000323 if (PendingLoads.size() == 1) {
324 SDOperand Root = PendingLoads[0];
325 DAG.setRoot(Root);
326 PendingLoads.clear();
327 return Root;
328 }
329
330 // Otherwise, we have to make a token factor node.
331 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
332 PendingLoads.clear();
333 DAG.setRoot(Root);
334 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000335 }
336
Chris Lattner1c08c712005-01-07 07:47:53 +0000337 void visit(Instruction &I) { visit(I.getOpcode(), I); }
338
339 void visit(unsigned Opcode, User &I) {
340 switch (Opcode) {
341 default: assert(0 && "Unknown instruction type encountered!");
342 abort();
343 // Build the switch statement using the Instruction.def file.
344#define HANDLE_INST(NUM, OPCODE, CLASS) \
345 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
346#include "llvm/Instruction.def"
347 }
348 }
349
350 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
351
352
353 SDOperand getIntPtrConstant(uint64_t Val) {
354 return DAG.getConstant(Val, TLI.getPointerTy());
355 }
356
357 SDOperand getValue(const Value *V) {
358 SDOperand &N = NodeMap[V];
359 if (N.Val) return N;
360
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000361 const Type *VTy = V->getType();
362 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner1c08c712005-01-07 07:47:53 +0000363 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
364 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
365 visit(CE->getOpcode(), *CE);
366 assert(N.Val && "visit didn't populate the ValueMap!");
367 return N;
368 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
369 return N = DAG.getGlobalAddress(GV, VT);
370 } else if (isa<ConstantPointerNull>(C)) {
371 return N = DAG.getConstant(0, TLI.getPointerTy());
372 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000373 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000374 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
375 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000376 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
377 unsigned NumElements = PTy->getNumElements();
378 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
379 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
380
381 // Now that we know the number and type of the elements, push a
382 // Constant or ConstantFP node onto the ops list for each element of
383 // the packed constant.
384 std::vector<SDOperand> Ops;
Chris Lattner3b841e92005-12-21 02:43:26 +0000385 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
386 if (MVT::isFloatingPoint(PVT)) {
387 for (unsigned i = 0; i != NumElements; ++i) {
388 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
389 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
390 }
391 } else {
392 for (unsigned i = 0; i != NumElements; ++i) {
393 const ConstantIntegral *El =
394 cast<ConstantIntegral>(CP->getOperand(i));
395 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
396 }
397 }
398 } else {
399 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
400 SDOperand Op;
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000401 if (MVT::isFloatingPoint(PVT))
Chris Lattner3b841e92005-12-21 02:43:26 +0000402 Op = DAG.getConstantFP(0, PVT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000403 else
Chris Lattner3b841e92005-12-21 02:43:26 +0000404 Op = DAG.getConstant(0, PVT);
405 Ops.assign(NumElements, Op);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000406 }
Chris Lattner3b841e92005-12-21 02:43:26 +0000407
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000408 // Handle the case where we have a 1-element vector, in which
409 // case we want to immediately turn it into a scalar constant.
Nate Begemancc827e62005-12-07 19:48:11 +0000410 if (Ops.size() == 1) {
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000411 return N = Ops[0];
Nate Begemancc827e62005-12-07 19:48:11 +0000412 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
413 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
414 } else {
415 // If the packed type isn't legal, then create a ConstantVec node with
416 // generic Vector type instead.
417 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
418 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000419 } else {
420 // Canonicalize all constant ints to be unsigned.
421 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
422 }
423
424 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
425 std::map<const AllocaInst*, int>::iterator SI =
426 FuncInfo.StaticAllocaMap.find(AI);
427 if (SI != FuncInfo.StaticAllocaMap.end())
428 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
429 }
430
431 std::map<const Value*, unsigned>::const_iterator VMI =
432 FuncInfo.ValueMap.find(V);
433 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000434
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +0000435 unsigned InReg = VMI->second;
436
437 // If this type is not legal, make it so now.
438 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
439
440 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
441 if (DestVT < VT) {
442 // Source must be expanded. This input value is actually coming from the
443 // register pair VMI->second and VMI->second+1.
444 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
445 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
446 } else {
447 if (DestVT > VT) { // Promotion case
448 if (MVT::isFloatingPoint(VT))
449 N = DAG.getNode(ISD::FP_ROUND, VT, N);
450 else
451 N = DAG.getNode(ISD::TRUNCATE, VT, N);
452 }
453 }
454
455 return N;
Chris Lattner1c08c712005-01-07 07:47:53 +0000456 }
457
458 const SDOperand &setValue(const Value *V, SDOperand NewN) {
459 SDOperand &N = NodeMap[V];
460 assert(N.Val == 0 && "Already set a value for this node!");
461 return N = NewN;
462 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000463
Chris Lattner864635a2006-02-22 22:37:12 +0000464 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
465 MVT::ValueType VT,
466 bool OutReg, bool InReg,
467 std::set<unsigned> &OutputRegs,
468 std::set<unsigned> &InputRegs);
469
Chris Lattner1c08c712005-01-07 07:47:53 +0000470 // Terminator instructions.
471 void visitRet(ReturnInst &I);
472 void visitBr(BranchInst &I);
473 void visitUnreachable(UnreachableInst &I) { /* noop */ }
474
475 // These all get lowered before this pass.
Robert Bocchinoc0f4cd92006-01-10 19:04:57 +0000476 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino4eb2e3a2006-01-17 20:06:42 +0000477 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000478 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
479 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
480 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
481
482 //
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000483 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000484 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000485 void visitAdd(User &I) {
486 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000487 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000488 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000489 void visitMul(User &I) {
490 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000491 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000492 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000493 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000494 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000495 }
496 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000497 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000498 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000499 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000500 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
501 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
502 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begemane21ea612005-11-18 07:42:56 +0000503 void visitShl(User &I) { visitShift(I, ISD::SHL); }
504 void visitShr(User &I) {
505 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000506 }
507
508 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
509 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
510 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
511 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
512 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
513 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
514 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
515
516 void visitGetElementPtr(User &I);
517 void visitCast(User &I);
518 void visitSelect(User &I);
519 //
520
521 void visitMalloc(MallocInst &I);
522 void visitFree(FreeInst &I);
523 void visitAlloca(AllocaInst &I);
524 void visitLoad(LoadInst &I);
525 void visitStore(StoreInst &I);
526 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
527 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000528 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000529 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000530
Chris Lattner1c08c712005-01-07 07:47:53 +0000531 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000532 void visitVAArg(VAArgInst &I);
533 void visitVAEnd(CallInst &I);
534 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000535 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000536
Chris Lattner7041ee32005-01-11 05:56:49 +0000537 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000538
539 void visitUserOp1(Instruction &I) {
540 assert(0 && "UserOp1 should not exist at instruction selection time!");
541 abort();
542 }
543 void visitUserOp2(Instruction &I) {
544 assert(0 && "UserOp2 should not exist at instruction selection time!");
545 abort();
546 }
547};
548} // end namespace llvm
549
550void SelectionDAGLowering::visitRet(ReturnInst &I) {
551 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000552 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000553 return;
554 }
Nate Begemanee625572006-01-27 21:09:22 +0000555 std::vector<SDOperand> NewValues;
556 NewValues.push_back(getRoot());
557 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
558 SDOperand RetOp = getValue(I.getOperand(i));
559
560 // If this is an integer return value, we need to promote it ourselves to
561 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
562 // than sign/zero.
563 if (MVT::isInteger(RetOp.getValueType()) &&
564 RetOp.getValueType() < MVT::i64) {
565 MVT::ValueType TmpVT;
566 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
567 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
568 else
569 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000570
Nate Begemanee625572006-01-27 21:09:22 +0000571 if (I.getOperand(i)->getType()->isSigned())
572 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
573 else
574 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
575 }
576 NewValues.push_back(RetOp);
Chris Lattner1c08c712005-01-07 07:47:53 +0000577 }
Nate Begemanee625572006-01-27 21:09:22 +0000578 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner1c08c712005-01-07 07:47:53 +0000579}
580
581void SelectionDAGLowering::visitBr(BranchInst &I) {
582 // Update machine-CFG edges.
583 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000584
585 // Figure out which block is immediately after the current one.
586 MachineBasicBlock *NextBlock = 0;
587 MachineFunction::iterator BBI = CurMBB;
588 if (++BBI != CurMBB->getParent()->end())
589 NextBlock = BBI;
590
591 if (I.isUnconditional()) {
592 // If this is not a fall-through branch, emit the branch.
593 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000594 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000595 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000596 } else {
597 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000598
599 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000600 if (Succ1MBB == NextBlock) {
601 // If the condition is false, fall through. This means we should branch
602 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000603 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000604 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000605 } else if (Succ0MBB == NextBlock) {
606 // If the condition is true, fall through. This means we should branch if
607 // the condition is false to Succ #1. Invert the condition first.
608 SDOperand True = DAG.getConstant(1, Cond.getValueType());
609 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000610 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000611 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000612 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000613 std::vector<SDOperand> Ops;
614 Ops.push_back(getRoot());
Evan Cheng298ebf22006-02-16 08:27:56 +0000615 // If the false case is the current basic block, then this is a self
616 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
617 // adds an extra instruction in the loop. Instead, invert the
618 // condition and emit "Loop: ... br!cond Loop; br Out.
619 if (CurMBB == Succ1MBB) {
620 std::swap(Succ0MBB, Succ1MBB);
621 SDOperand True = DAG.getConstant(1, Cond.getValueType());
622 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
623 }
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000624 Ops.push_back(Cond);
625 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
626 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
627 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000628 }
629 }
630}
631
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000632void SelectionDAGLowering::visitSub(User &I) {
633 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000634 if (I.getType()->isFloatingPoint()) {
635 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
636 if (CFP->isExactlyValue(-0.0)) {
637 SDOperand Op2 = getValue(I.getOperand(1));
638 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
639 return;
640 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000641 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000642 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000643}
644
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000645void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
646 unsigned VecOp) {
647 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000648 SDOperand Op1 = getValue(I.getOperand(0));
649 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000650
Chris Lattnerb67eb912005-11-19 18:40:42 +0000651 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000652 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
653 } else if (Ty->isFloatingPoint()) {
654 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
655 } else {
656 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000657 unsigned NumElements = PTy->getNumElements();
658 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000659 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000660
661 // Immediately scalarize packed types containing only one element, so that
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000662 // the Legalize pass does not have to deal with them. Similarly, if the
663 // abstract vector is going to turn into one that the target natively
664 // supports, generate that type now so that Legalize doesn't have to deal
665 // with that either. These steps ensure that Legalize only has to handle
666 // vector types in its Expand case.
667 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman4ef3b812005-11-22 01:29:36 +0000668 if (NumElements == 1) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000669 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000670 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
671 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000672 } else {
673 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
674 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemanab48be32005-11-22 18:16:00 +0000675 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000676 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000677 }
Nate Begemane21ea612005-11-18 07:42:56 +0000678}
Chris Lattner2c49f272005-01-19 22:31:21 +0000679
Nate Begemane21ea612005-11-18 07:42:56 +0000680void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
681 SDOperand Op1 = getValue(I.getOperand(0));
682 SDOperand Op2 = getValue(I.getOperand(1));
683
684 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
685
Chris Lattner1c08c712005-01-07 07:47:53 +0000686 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
687}
688
689void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
690 ISD::CondCode UnsignedOpcode) {
691 SDOperand Op1 = getValue(I.getOperand(0));
692 SDOperand Op2 = getValue(I.getOperand(1));
693 ISD::CondCode Opcode = SignedOpcode;
694 if (I.getOperand(0)->getType()->isUnsigned())
695 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000696 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000697}
698
699void SelectionDAGLowering::visitSelect(User &I) {
700 SDOperand Cond = getValue(I.getOperand(0));
701 SDOperand TrueVal = getValue(I.getOperand(1));
702 SDOperand FalseVal = getValue(I.getOperand(2));
703 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
704 TrueVal, FalseVal));
705}
706
707void SelectionDAGLowering::visitCast(User &I) {
708 SDOperand N = getValue(I.getOperand(0));
709 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
710 MVT::ValueType DestTy = TLI.getValueType(I.getType());
711
712 if (N.getValueType() == DestTy) {
713 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000714 } else if (DestTy == MVT::i1) {
715 // Cast to bool is a comparison against zero, not truncation to zero.
716 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
717 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000718 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000719 } else if (isInteger(SrcTy)) {
720 if (isInteger(DestTy)) { // Int -> Int cast
721 if (DestTy < SrcTy) // Truncating cast?
722 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
723 else if (I.getOperand(0)->getType()->isSigned())
724 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
725 else
726 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
727 } else { // Int -> FP cast
728 if (I.getOperand(0)->getType()->isSigned())
729 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
730 else
731 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
732 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000733 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000734 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
735 if (isFloatingPoint(DestTy)) { // FP -> FP cast
736 if (DestTy < SrcTy) // Rounding cast?
737 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
738 else
739 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
740 } else { // FP -> Int cast.
741 if (I.getType()->isSigned())
742 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
743 else
744 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
745 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000746 }
747}
748
749void SelectionDAGLowering::visitGetElementPtr(User &I) {
750 SDOperand N = getValue(I.getOperand(0));
751 const Type *Ty = I.getOperand(0)->getType();
752 const Type *UIntPtrTy = TD.getIntPtrType();
753
754 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
755 OI != E; ++OI) {
756 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +0000757 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000758 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
759 if (Field) {
760 // N = N + Offset
761 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
762 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000763 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000764 }
765 Ty = StTy->getElementType(Field);
766 } else {
767 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +0000768
Chris Lattner7c0104b2005-11-09 04:45:33 +0000769 // If this is a constant subscript, handle it quickly.
770 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
771 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +0000772
Chris Lattner7c0104b2005-11-09 04:45:33 +0000773 uint64_t Offs;
774 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
775 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
776 else
777 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
778 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
779 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +0000780 }
Chris Lattner7c0104b2005-11-09 04:45:33 +0000781
782 // N = N + Idx * ElementSize;
783 uint64_t ElementSize = TD.getTypeSize(Ty);
784 SDOperand IdxN = getValue(Idx);
785
786 // If the index is smaller or larger than intptr_t, truncate or extend
787 // it.
788 if (IdxN.getValueType() < N.getValueType()) {
789 if (Idx->getType()->isSigned())
790 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
791 else
792 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
793 } else if (IdxN.getValueType() > N.getValueType())
794 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
795
796 // If this is a multiply by a power of two, turn it into a shl
797 // immediately. This is a very common case.
798 if (isPowerOf2_64(ElementSize)) {
799 unsigned Amt = Log2_64(ElementSize);
800 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +0000801 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +0000802 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
803 continue;
804 }
805
806 SDOperand Scale = getIntPtrConstant(ElementSize);
807 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
808 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +0000809 }
810 }
811 setValue(&I, N);
812}
813
814void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
815 // If this is a fixed sized alloca in the entry block of the function,
816 // allocate it statically on the stack.
817 if (FuncInfo.StaticAllocaMap.count(&I))
818 return; // getValue will auto-populate this.
819
820 const Type *Ty = I.getAllocatedType();
821 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000822 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
823 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +0000824
825 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000826 MVT::ValueType IntPtr = TLI.getPointerTy();
827 if (IntPtr < AllocSize.getValueType())
828 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
829 else if (IntPtr > AllocSize.getValueType())
830 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000831
Chris Lattner68cd65e2005-01-22 23:04:37 +0000832 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000833 getIntPtrConstant(TySize));
834
835 // Handle alignment. If the requested alignment is less than or equal to the
836 // stack alignment, ignore it and round the size of the allocation up to the
837 // stack alignment size. If the size is greater than the stack alignment, we
838 // note this in the DYNAMIC_STACKALLOC node.
839 unsigned StackAlign =
840 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
841 if (Align <= StackAlign) {
842 Align = 0;
843 // Add SA-1 to the size.
844 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
845 getIntPtrConstant(StackAlign-1));
846 // Mask out the low bits for alignment purposes.
847 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
848 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
849 }
850
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000851 std::vector<MVT::ValueType> VTs;
852 VTs.push_back(AllocSize.getValueType());
853 VTs.push_back(MVT::Other);
854 std::vector<SDOperand> Ops;
855 Ops.push_back(getRoot());
856 Ops.push_back(AllocSize);
857 Ops.push_back(getIntPtrConstant(Align));
858 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000859 DAG.setRoot(setValue(&I, DSA).getValue(1));
860
861 // Inform the Frame Information that we have just allocated a variable-sized
862 // object.
863 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
864}
865
Chris Lattner36ce6912005-11-29 06:21:05 +0000866/// getStringValue - Turn an LLVM constant pointer that eventually points to a
867/// global into a string value. Return an empty string if we can't do it.
868///
Evan Cheng74d0aa92006-02-15 21:59:04 +0000869static std::string getStringValue(GlobalVariable *GV, unsigned Offset = 0) {
870 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
871 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
872 if (Init->isString()) {
873 std::string Result = Init->getAsString();
874 if (Offset < Result.size()) {
875 // If we are pointing INTO The string, erase the beginning...
876 Result.erase(Result.begin(), Result.begin()+Offset);
877 return Result;
Chris Lattner36ce6912005-11-29 06:21:05 +0000878 }
879 }
880 }
881 return "";
882}
Chris Lattner1c08c712005-01-07 07:47:53 +0000883
884void SelectionDAGLowering::visitLoad(LoadInst &I) {
885 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000886
Chris Lattnerd3948112005-01-17 22:19:26 +0000887 SDOperand Root;
888 if (I.isVolatile())
889 Root = getRoot();
890 else {
891 // Do not serialize non-volatile loads against each other.
892 Root = DAG.getRoot();
893 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000894
895 const Type *Ty = I.getType();
896 SDOperand L;
897
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000898 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000899 unsigned NumElements = PTy->getNumElements();
900 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000901 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000902
903 // Immediately scalarize packed types containing only one element, so that
904 // the Legalize pass does not have to deal with them.
905 if (NumElements == 1) {
906 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000907 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
908 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000909 } else {
910 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
911 DAG.getSrcValue(I.getOperand(0)));
912 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000913 } else {
914 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
915 DAG.getSrcValue(I.getOperand(0)));
916 }
Chris Lattnerd3948112005-01-17 22:19:26 +0000917 setValue(&I, L);
918
919 if (I.isVolatile())
920 DAG.setRoot(L.getValue(1));
921 else
922 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000923}
924
925
926void SelectionDAGLowering::visitStore(StoreInst &I) {
927 Value *SrcV = I.getOperand(0);
928 SDOperand Src = getValue(SrcV);
929 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000930 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000931 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000932}
933
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000934/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
935/// we want to emit this as a call to a named external function, return the name
936/// otherwise lower it and return null.
937const char *
938SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
939 switch (Intrinsic) {
940 case Intrinsic::vastart: visitVAStart(I); return 0;
941 case Intrinsic::vaend: visitVAEnd(I); return 0;
942 case Intrinsic::vacopy: visitVACopy(I); return 0;
943 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
944 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
945 case Intrinsic::setjmp:
946 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
947 break;
948 case Intrinsic::longjmp:
949 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
950 break;
951 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
952 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
953 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
954
955 case Intrinsic::readport:
956 case Intrinsic::readio: {
957 std::vector<MVT::ValueType> VTs;
958 VTs.push_back(TLI.getValueType(I.getType()));
959 VTs.push_back(MVT::Other);
960 std::vector<SDOperand> Ops;
961 Ops.push_back(getRoot());
962 Ops.push_back(getValue(I.getOperand(1)));
963 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
964 ISD::READPORT : ISD::READIO, VTs, Ops);
965
966 setValue(&I, Tmp);
967 DAG.setRoot(Tmp.getValue(1));
968 return 0;
969 }
970 case Intrinsic::writeport:
971 case Intrinsic::writeio:
972 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
973 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
974 getRoot(), getValue(I.getOperand(1)),
975 getValue(I.getOperand(2))));
976 return 0;
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000977
Chris Lattner86cb6432005-12-13 17:40:33 +0000978 case Intrinsic::dbg_stoppoint: {
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000979 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
980 return "llvm_debugger_stop";
Chris Lattner36ce6912005-11-29 06:21:05 +0000981
Jim Laskeyce72b172006-02-11 01:01:30 +0000982 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
983 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) {
984 std::vector<SDOperand> Ops;
Chris Lattner36ce6912005-11-29 06:21:05 +0000985
Jim Laskeyce72b172006-02-11 01:01:30 +0000986 // Input Chain
987 Ops.push_back(getRoot());
988
989 // line number
990 Ops.push_back(getValue(I.getOperand(2)));
991
992 // column
993 Ops.push_back(getValue(I.getOperand(3)));
Chris Lattner36ce6912005-11-29 06:21:05 +0000994
Jim Laskeyd96185a2006-02-13 12:50:39 +0000995 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
Jim Laskeyce72b172006-02-11 01:01:30 +0000996 assert(DD && "Not a debug information descriptor");
997 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
998 assert(CompileUnit && "Not a compile unit");
999 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1000 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1001
1002 if (Ops.size() == 5) // Found filename/workingdir.
1003 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner86cb6432005-12-13 17:40:33 +00001004 }
1005
Chris Lattnerd67b3a82005-12-03 18:50:48 +00001006 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001007 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001008 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001009 case Intrinsic::dbg_region_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001010 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1011 return "llvm_dbg_region_start";
1012 if (I.getType() != Type::VoidTy)
1013 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1014 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001015 case Intrinsic::dbg_region_end:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001016 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1017 return "llvm_dbg_region_end";
1018 if (I.getType() != Type::VoidTy)
1019 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1020 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001021 case Intrinsic::dbg_func_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001022 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1023 return "llvm_dbg_subprogram";
1024 if (I.getType() != Type::VoidTy)
1025 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1026 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001027 case Intrinsic::dbg_declare:
1028 if (I.getType() != Type::VoidTy)
1029 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1030 return 0;
1031
Reid Spencer0b118202006-01-16 21:12:35 +00001032 case Intrinsic::isunordered_f32:
1033 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001034 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1035 getValue(I.getOperand(2)), ISD::SETUO));
1036 return 0;
1037
Reid Spencer0b118202006-01-16 21:12:35 +00001038 case Intrinsic::sqrt_f32:
1039 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001040 setValue(&I, DAG.getNode(ISD::FSQRT,
1041 getValue(I.getOperand(1)).getValueType(),
1042 getValue(I.getOperand(1))));
1043 return 0;
1044 case Intrinsic::pcmarker: {
1045 SDOperand Tmp = getValue(I.getOperand(1));
1046 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1047 return 0;
1048 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001049 case Intrinsic::readcyclecounter: {
1050 std::vector<MVT::ValueType> VTs;
1051 VTs.push_back(MVT::i64);
1052 VTs.push_back(MVT::Other);
1053 std::vector<SDOperand> Ops;
1054 Ops.push_back(getRoot());
1055 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1056 setValue(&I, Tmp);
1057 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001058 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001059 }
Nate Begemand88fc032006-01-14 03:14:10 +00001060 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001061 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001062 case Intrinsic::bswap_i64:
1063 setValue(&I, DAG.getNode(ISD::BSWAP,
1064 getValue(I.getOperand(1)).getValueType(),
1065 getValue(I.getOperand(1))));
1066 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001067 case Intrinsic::cttz_i8:
1068 case Intrinsic::cttz_i16:
1069 case Intrinsic::cttz_i32:
1070 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001071 setValue(&I, DAG.getNode(ISD::CTTZ,
1072 getValue(I.getOperand(1)).getValueType(),
1073 getValue(I.getOperand(1))));
1074 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001075 case Intrinsic::ctlz_i8:
1076 case Intrinsic::ctlz_i16:
1077 case Intrinsic::ctlz_i32:
1078 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001079 setValue(&I, DAG.getNode(ISD::CTLZ,
1080 getValue(I.getOperand(1)).getValueType(),
1081 getValue(I.getOperand(1))));
1082 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001083 case Intrinsic::ctpop_i8:
1084 case Intrinsic::ctpop_i16:
1085 case Intrinsic::ctpop_i32:
1086 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001087 setValue(&I, DAG.getNode(ISD::CTPOP,
1088 getValue(I.getOperand(1)).getValueType(),
1089 getValue(I.getOperand(1))));
1090 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001091 case Intrinsic::stacksave: {
1092 std::vector<MVT::ValueType> VTs;
1093 VTs.push_back(TLI.getPointerTy());
1094 VTs.push_back(MVT::Other);
1095 std::vector<SDOperand> Ops;
1096 Ops.push_back(getRoot());
1097 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1098 setValue(&I, Tmp);
1099 DAG.setRoot(Tmp.getValue(1));
1100 return 0;
1101 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001102 case Intrinsic::stackrestore: {
1103 SDOperand Tmp = getValue(I.getOperand(1));
1104 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001105 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001106 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001107 case Intrinsic::prefetch:
1108 // FIXME: Currently discarding prefetches.
1109 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001110 default:
1111 std::cerr << I;
1112 assert(0 && "This intrinsic is not implemented yet!");
1113 return 0;
1114 }
1115}
1116
1117
Chris Lattner1c08c712005-01-07 07:47:53 +00001118void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001119 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001120 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001121 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001122 if (unsigned IID = F->getIntrinsicID()) {
1123 RenameFn = visitIntrinsicCall(I, IID);
1124 if (!RenameFn)
1125 return;
1126 } else { // Not an LLVM intrinsic.
1127 const std::string &Name = F->getName();
1128 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001129 if (I.getNumOperands() == 2 && // Basic sanity checks.
1130 I.getOperand(1)->getType()->isFloatingPoint() &&
1131 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001132 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001133 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1134 return;
1135 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001136 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001137 if (I.getNumOperands() == 2 && // Basic sanity checks.
1138 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001139 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001140 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001141 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1142 return;
1143 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001144 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001145 if (I.getNumOperands() == 2 && // Basic sanity checks.
1146 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001147 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001148 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001149 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1150 return;
1151 }
1152 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001153 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001154 } else if (isa<InlineAsm>(I.getOperand(0))) {
1155 visitInlineAsm(I);
1156 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001157 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001158
Chris Lattner64e14b12005-01-08 22:48:57 +00001159 SDOperand Callee;
1160 if (!RenameFn)
1161 Callee = getValue(I.getOperand(0));
1162 else
1163 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001164 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001165 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001166 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1167 Value *Arg = I.getOperand(i);
1168 SDOperand ArgNode = getValue(Arg);
1169 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1170 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001171
Nate Begeman8e21e712005-03-26 01:29:23 +00001172 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1173 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001174
Chris Lattnercf5734d2005-01-08 19:26:18 +00001175 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001176 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001177 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001178 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001179 setValue(&I, Result.first);
1180 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001181}
1182
Chris Lattner864635a2006-02-22 22:37:12 +00001183SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001184 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00001185 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1186 Chain = Val.getValue(1);
1187 Flag = Val.getValue(2);
1188
1189 // If the result was expanded, copy from the top part.
1190 if (Regs.size() > 1) {
1191 assert(Regs.size() == 2 &&
1192 "Cannot expand to more than 2 elts yet!");
1193 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1194 Chain = Val.getValue(1);
1195 Flag = Val.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00001196 if (DAG.getTargetLoweringInfo().isLittleEndian())
1197 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1198 else
1199 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00001200 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001201
Chris Lattner864635a2006-02-22 22:37:12 +00001202 // Otherwise, if the return value was promoted, truncate it to the
1203 // appropriate type.
1204 if (RegVT == ValueVT)
1205 return Val;
1206
1207 if (MVT::isInteger(RegVT))
1208 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1209 else
1210 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1211}
1212
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001213/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1214/// specified value into the registers specified by this object. This uses
1215/// Chain/Flag as the input and updates them for the output Chain/Flag.
1216void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001217 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001218 if (Regs.size() == 1) {
1219 // If there is a single register and the types differ, this must be
1220 // a promotion.
1221 if (RegVT != ValueVT) {
1222 if (MVT::isInteger(RegVT))
1223 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1224 else
1225 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1226 }
1227 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1228 Flag = Chain.getValue(1);
1229 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00001230 std::vector<unsigned> R(Regs);
1231 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1232 std::reverse(R.begin(), R.end());
1233
1234 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001235 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1236 DAG.getConstant(i, MVT::i32));
Chris Lattner9f6637d2006-02-23 20:06:57 +00001237 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001238 Flag = Chain.getValue(1);
1239 }
1240 }
1241}
Chris Lattner864635a2006-02-22 22:37:12 +00001242
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001243/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1244/// operand list. This adds the code marker and includes the number of
1245/// values added into it.
1246void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001247 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001248 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1249 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1250 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1251}
Chris Lattner864635a2006-02-22 22:37:12 +00001252
1253/// isAllocatableRegister - If the specified register is safe to allocate,
1254/// i.e. it isn't a stack pointer or some other special register, return the
1255/// register class for the register. Otherwise, return null.
1256static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001257isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1258 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1259 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1260 E = MRI->regclass_end(); RCI != E; ++RCI) {
1261 const TargetRegisterClass *RC = *RCI;
1262 // If none of the the value types for this register class are valid, we
1263 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1264 bool isLegal = false;
1265 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1266 I != E; ++I) {
1267 if (TLI.isTypeLegal(*I)) {
1268 isLegal = true;
1269 break;
1270 }
1271 }
1272
1273 if (!isLegal) continue;
1274
Chris Lattner864635a2006-02-22 22:37:12 +00001275 // NOTE: This isn't ideal. In particular, this might allocate the
1276 // frame pointer in functions that need it (due to them not being taken
1277 // out of allocation, because a variable sized allocation hasn't been seen
1278 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001279 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1280 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner864635a2006-02-22 22:37:12 +00001281 if (*I == Reg)
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001282 return RC;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001283 }
1284 return 0;
Chris Lattner864635a2006-02-22 22:37:12 +00001285}
1286
1287RegsForValue SelectionDAGLowering::
1288GetRegistersForValue(const std::string &ConstrCode,
1289 MVT::ValueType VT, bool isOutReg, bool isInReg,
1290 std::set<unsigned> &OutputRegs,
1291 std::set<unsigned> &InputRegs) {
1292 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1293 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1294 std::vector<unsigned> Regs;
1295
1296 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1297 MVT::ValueType RegVT;
1298 MVT::ValueType ValueVT = VT;
1299
1300 if (PhysReg.first) {
1301 if (VT == MVT::Other)
1302 ValueVT = *PhysReg.second->vt_begin();
1303 RegVT = VT;
1304
1305 // This is a explicit reference to a physical register.
1306 Regs.push_back(PhysReg.first);
1307
1308 // If this is an expanded reference, add the rest of the regs to Regs.
1309 if (NumRegs != 1) {
1310 RegVT = *PhysReg.second->vt_begin();
1311 TargetRegisterClass::iterator I = PhysReg.second->begin();
1312 TargetRegisterClass::iterator E = PhysReg.second->end();
1313 for (; *I != PhysReg.first; ++I)
1314 assert(I != E && "Didn't find reg!");
1315
1316 // Already added the first reg.
1317 --NumRegs; ++I;
1318 for (; NumRegs; --NumRegs, ++I) {
1319 assert(I != E && "Ran out of registers to allocate!");
1320 Regs.push_back(*I);
1321 }
1322 }
1323 return RegsForValue(Regs, RegVT, ValueVT);
1324 }
1325
1326 // This is a reference to a register class. Allocate NumRegs consecutive,
1327 // available, registers from the class.
1328 std::vector<unsigned> RegClassRegs =
1329 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1330
1331 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1332 MachineFunction &MF = *CurMBB->getParent();
1333 unsigned NumAllocated = 0;
1334 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1335 unsigned Reg = RegClassRegs[i];
1336 // See if this register is available.
1337 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1338 (isInReg && InputRegs.count(Reg))) { // Already used.
1339 // Make sure we find consecutive registers.
1340 NumAllocated = 0;
1341 continue;
1342 }
1343
1344 // Check to see if this register is allocatable (i.e. don't give out the
1345 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001346 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00001347 if (!RC) {
1348 // Make sure we find consecutive registers.
1349 NumAllocated = 0;
1350 continue;
1351 }
1352
1353 // Okay, this register is good, we can use it.
1354 ++NumAllocated;
1355
1356 // If we allocated enough consecutive
1357 if (NumAllocated == NumRegs) {
1358 unsigned RegStart = (i-NumAllocated)+1;
1359 unsigned RegEnd = i+1;
1360 // Mark all of the allocated registers used.
1361 for (unsigned i = RegStart; i != RegEnd; ++i) {
1362 unsigned Reg = RegClassRegs[i];
1363 Regs.push_back(Reg);
1364 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1365 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1366 }
1367
1368 return RegsForValue(Regs, *RC->vt_begin(), VT);
1369 }
1370 }
1371
1372 // Otherwise, we couldn't allocate enough registers for this.
1373 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00001374}
1375
Chris Lattner864635a2006-02-22 22:37:12 +00001376
Chris Lattnerce7518c2006-01-26 22:24:51 +00001377/// visitInlineAsm - Handle a call to an InlineAsm object.
1378///
1379void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1380 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1381
1382 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1383 MVT::Other);
1384
1385 // Note, we treat inline asms both with and without side-effects as the same.
1386 // If an inline asm doesn't have side effects and doesn't access memory, we
1387 // could not choose to not chain it.
1388 bool hasSideEffects = IA->hasSideEffects();
1389
Chris Lattner2cc2f662006-02-01 01:28:23 +00001390 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001391 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00001392
1393 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1394 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1395 /// if it is a def of that register.
1396 std::vector<SDOperand> AsmNodeOperands;
1397 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1398 AsmNodeOperands.push_back(AsmStr);
1399
1400 SDOperand Chain = getRoot();
1401 SDOperand Flag;
1402
Chris Lattner4e4b5762006-02-01 18:59:47 +00001403 // We fully assign registers here at isel time. This is not optimal, but
1404 // should work. For register classes that correspond to LLVM classes, we
1405 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1406 // over the constraints, collecting fixed registers that we know we can't use.
1407 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001408 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001409 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1410 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1411 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00001412
Chris Lattner1efa40f2006-02-22 00:56:39 +00001413 MVT::ValueType OpVT;
1414
1415 // Compute the value type for each operand and add it to ConstraintVTs.
1416 switch (Constraints[i].Type) {
1417 case InlineAsm::isOutput:
1418 if (!Constraints[i].isIndirectOutput) {
1419 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1420 OpVT = TLI.getValueType(I.getType());
1421 } else {
1422 Value *CallOperand = I.getOperand(OpNum);
1423 const Type *OpTy = CallOperand->getType();
1424 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 Lattner864635a2006-02-22 22:37:12 +00001439 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1440 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00001441
Chris Lattner864635a2006-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 Lattner4e4b5762006-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 Lattner864635a2006-02-22 22:37:12 +00001451 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-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 Lattner2223aea2006-02-02 00:25:23 +00001454 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00001455 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001456 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001457 case InlineAsm::isInput:
1458 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001459 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00001460 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001461 case InlineAsm::isClobber:
1462 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00001463 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1464 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001465 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001466 }
1467 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00001468
Chris Lattner0f0b7d42006-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 Lattner864635a2006-02-22 22:37:12 +00001471 RegsForValue RetValRegs;
1472 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001473 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001474
Chris Lattner6656dd12006-01-31 02:03:41 +00001475 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-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 Lattner1efa40f2006-02-22 00:56:39 +00001478
Chris Lattner2cc2f662006-02-01 01:28:23 +00001479 switch (Constraints[i].Type) {
1480 case InlineAsm::isOutput: {
Chris Lattner864635a2006-02-22 22:37:12 +00001481 // If this is an early-clobber output, or if there is an input
1482 // constraint that matches this, we need to reserve the input register
1483 // so no other inputs allocate to it.
1484 bool UsesInputRegister = false;
1485 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1486 UsesInputRegister = true;
1487
1488 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00001489 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00001490 RegsForValue Regs =
1491 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1492 true, UsesInputRegister,
1493 OutputRegs, InputRegs);
1494 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner1efa40f2006-02-22 00:56:39 +00001495
Chris Lattner2cc2f662006-02-01 01:28:23 +00001496 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00001497 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00001498 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00001499 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00001500 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00001501 } else {
Chris Lattner1efa40f2006-02-22 00:56:39 +00001502 Value *CallOperand = I.getOperand(OpNum);
Chris Lattner864635a2006-02-22 22:37:12 +00001503 IndirectStoresToEmit.push_back(std::make_pair(Regs, CallOperand));
Chris Lattner2cc2f662006-02-01 01:28:23 +00001504 OpNum++; // Consumes a call operand.
1505 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001506
1507 // Add information to the INLINEASM node to know that this register is
1508 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001509 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001510 break;
1511 }
1512 case InlineAsm::isInput: {
Chris Lattner1efa40f2006-02-22 00:56:39 +00001513 Value *CallOperand = I.getOperand(OpNum);
Chris Lattner4e4b5762006-02-01 18:59:47 +00001514 OpNum++; // Consumes a call operand.
Chris Lattner2223aea2006-02-02 00:25:23 +00001515
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001516 SDOperand InOperandVal = getValue(CallOperand);
Chris Lattner3d81fee2006-02-04 02:16:44 +00001517
Chris Lattner2223aea2006-02-02 00:25:23 +00001518 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1519 // If this is required to match an output register we have already set,
1520 // just use its register.
1521 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00001522
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001523 // Scan until we find the definition we already emitted of this operand.
1524 // When we find it, create a RegsForValue operand.
1525 unsigned CurOp = 2; // The first operand.
1526 for (; OperandNo; --OperandNo) {
1527 // Advance to the next operand.
1528 unsigned NumOps =
1529 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1530 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1531 "Skipped past definitions?");
1532 CurOp += (NumOps>>3)+1;
1533 }
1534
1535 unsigned NumOps =
1536 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1537 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1538 "Skipped past definitions?");
1539
1540 // Add NumOps>>3 registers to MatchedRegs.
1541 RegsForValue MatchedRegs;
1542 MatchedRegs.ValueVT = InOperandVal.getValueType();
1543 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1544 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1545 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1546 MatchedRegs.Regs.push_back(Reg);
1547 }
1548
1549 // Use the produced MatchedRegs object to
1550 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1551 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2223aea2006-02-02 00:25:23 +00001552 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00001553 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
Chris Lattner3d81fee2006-02-04 02:16:44 +00001554 if (ConstraintCode.size() == 1) // not a physreg name.
1555 CTy = TLI.getConstraintType(ConstraintCode[0]);
1556
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001557 if (CTy == TargetLowering::C_Other) {
Chris Lattner3d81fee2006-02-04 02:16:44 +00001558 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1559 assert(0 && "MATCH FAIL!");
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001560
1561 // Add information to the INLINEASM node to know about this input.
1562 unsigned ResOpType = 3 /*imm*/ | (1 << 3);
1563 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1564 AsmNodeOperands.push_back(InOperandVal);
Chris Lattner3d81fee2006-02-04 02:16:44 +00001565 break;
1566 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001567
1568 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1569
1570 // Copy the input into the appropriate registers.
1571 RegsForValue InRegs =
1572 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1573 false, true, OutputRegs, InputRegs);
1574 // FIXME: should be match fail.
1575 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1576
1577 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1578
1579 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
1580 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00001581 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001582 break;
1583 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001584 case InlineAsm::isClobber: {
1585 RegsForValue ClobberedRegs =
1586 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1587 OutputRegs, InputRegs);
1588 // Add the clobbered value to the operand list, so that the register
1589 // allocator is aware that the physreg got clobbered.
1590 if (!ClobberedRegs.Regs.empty())
1591 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001592 break;
1593 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001594 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001595 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001596
1597 // Finish up input operands.
1598 AsmNodeOperands[0] = Chain;
1599 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1600
1601 std::vector<MVT::ValueType> VTs;
1602 VTs.push_back(MVT::Other);
1603 VTs.push_back(MVT::Flag);
1604 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1605 Flag = Chain.getValue(1);
1606
Chris Lattner6656dd12006-01-31 02:03:41 +00001607 // If this asm returns a register value, copy the result from that register
1608 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00001609 if (!RetValRegs.Regs.empty())
1610 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00001611
Chris Lattner6656dd12006-01-31 02:03:41 +00001612 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1613
1614 // Process indirect outputs, first output all of the flagged copies out of
1615 // physregs.
1616 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00001617 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00001618 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00001619 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1620 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00001621 }
1622
1623 // Emit the non-flagged stores from the physregs.
1624 std::vector<SDOperand> OutChains;
1625 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1626 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1627 StoresToEmit[i].first,
1628 getValue(StoresToEmit[i].second),
1629 DAG.getSrcValue(StoresToEmit[i].second)));
1630 if (!OutChains.empty())
1631 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattnerce7518c2006-01-26 22:24:51 +00001632 DAG.setRoot(Chain);
1633}
1634
1635
Chris Lattner1c08c712005-01-07 07:47:53 +00001636void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1637 SDOperand Src = getValue(I.getOperand(0));
1638
1639 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00001640
1641 if (IntPtr < Src.getValueType())
1642 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1643 else if (IntPtr > Src.getValueType())
1644 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00001645
1646 // Scale the source by the type size.
1647 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1648 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1649 Src, getIntPtrConstant(ElementSize));
1650
1651 std::vector<std::pair<SDOperand, const Type*> > Args;
1652 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00001653
1654 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001655 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001656 DAG.getExternalSymbol("malloc", IntPtr),
1657 Args, DAG);
1658 setValue(&I, Result.first); // Pointers always fit in registers
1659 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001660}
1661
1662void SelectionDAGLowering::visitFree(FreeInst &I) {
1663 std::vector<std::pair<SDOperand, const Type*> > Args;
1664 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1665 TLI.getTargetData().getIntPtrType()));
1666 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00001667 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001668 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001669 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1670 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001671}
1672
Chris Lattner025c39b2005-08-26 20:54:47 +00001673// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1674// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1675// instructions are special in various ways, which require special support to
1676// insert. The specified MachineInstr is created but not inserted into any
1677// basic blocks, and the scheduler passes ownership of it to this method.
1678MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1679 MachineBasicBlock *MBB) {
1680 std::cerr << "If a target marks an instruction with "
1681 "'usesCustomDAGSchedInserter', it must implement "
1682 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1683 abort();
1684 return 0;
1685}
1686
Chris Lattner39ae3622005-01-09 00:00:49 +00001687void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001688 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1689 getValue(I.getOperand(1)),
1690 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00001691}
1692
1693void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001694 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1695 getValue(I.getOperand(0)),
1696 DAG.getSrcValue(I.getOperand(0)));
1697 setValue(&I, V);
1698 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00001699}
1700
1701void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001702 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1703 getValue(I.getOperand(1)),
1704 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001705}
1706
1707void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001708 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1709 getValue(I.getOperand(1)),
1710 getValue(I.getOperand(2)),
1711 DAG.getSrcValue(I.getOperand(1)),
1712 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001713}
1714
Chris Lattner39ae3622005-01-09 00:00:49 +00001715// It is always conservatively correct for llvm.returnaddress and
1716// llvm.frameaddress to return 0.
1717std::pair<SDOperand, SDOperand>
1718TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1719 unsigned Depth, SelectionDAG &DAG) {
1720 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00001721}
1722
Chris Lattner50381b62005-05-14 05:50:48 +00001723SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00001724 assert(0 && "LowerOperation not implemented for this target!");
1725 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001726 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00001727}
1728
Nate Begeman0aed7842006-01-28 03:14:31 +00001729SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1730 SelectionDAG &DAG) {
1731 assert(0 && "CustomPromoteOperation not implemented for this target!");
1732 abort();
1733 return SDOperand();
1734}
1735
Chris Lattner39ae3622005-01-09 00:00:49 +00001736void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1737 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1738 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00001739 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001740 setValue(&I, Result.first);
1741 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001742}
1743
Evan Cheng74d0aa92006-02-15 21:59:04 +00001744/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00001745/// operand.
1746static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00001747 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001748 MVT::ValueType CurVT = VT;
1749 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1750 uint64_t Val = C->getValue() & 255;
1751 unsigned Shift = 8;
1752 while (CurVT != MVT::i8) {
1753 Val = (Val << Shift) | Val;
1754 Shift <<= 1;
1755 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001756 }
1757 return DAG.getConstant(Val, VT);
1758 } else {
1759 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1760 unsigned Shift = 8;
1761 while (CurVT != MVT::i8) {
1762 Value =
1763 DAG.getNode(ISD::OR, VT,
1764 DAG.getNode(ISD::SHL, VT, Value,
1765 DAG.getConstant(Shift, MVT::i8)), Value);
1766 Shift <<= 1;
1767 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001768 }
1769
1770 return Value;
1771 }
1772}
1773
Evan Cheng74d0aa92006-02-15 21:59:04 +00001774/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1775/// used when a memcpy is turned into a memset when the source is a constant
1776/// string ptr.
1777static SDOperand getMemsetStringVal(MVT::ValueType VT,
1778 SelectionDAG &DAG, TargetLowering &TLI,
1779 std::string &Str, unsigned Offset) {
1780 MVT::ValueType CurVT = VT;
1781 uint64_t Val = 0;
1782 unsigned MSB = getSizeInBits(VT) / 8;
1783 if (TLI.isLittleEndian())
1784 Offset = Offset + MSB - 1;
1785 for (unsigned i = 0; i != MSB; ++i) {
1786 Val = (Val << 8) | Str[Offset];
1787 Offset += TLI.isLittleEndian() ? -1 : 1;
1788 }
1789 return DAG.getConstant(Val, VT);
1790}
1791
Evan Cheng1db92f92006-02-14 08:22:34 +00001792/// getMemBasePlusOffset - Returns base and offset node for the
1793static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1794 SelectionDAG &DAG, TargetLowering &TLI) {
1795 MVT::ValueType VT = Base.getValueType();
1796 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1797}
1798
Evan Chengc4f8eee2006-02-14 20:12:38 +00001799/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00001800/// to replace the memset / memcpy is below the threshold. It also returns the
1801/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00001802static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1803 unsigned Limit, uint64_t Size,
1804 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001805 MVT::ValueType VT;
1806
1807 if (TLI.allowsUnalignedMemoryAccesses()) {
1808 VT = MVT::i64;
1809 } else {
1810 switch (Align & 7) {
1811 case 0:
1812 VT = MVT::i64;
1813 break;
1814 case 4:
1815 VT = MVT::i32;
1816 break;
1817 case 2:
1818 VT = MVT::i16;
1819 break;
1820 default:
1821 VT = MVT::i8;
1822 break;
1823 }
1824 }
1825
Evan Cheng80e89d72006-02-14 09:11:59 +00001826 MVT::ValueType LVT = MVT::i64;
1827 while (!TLI.isTypeLegal(LVT))
1828 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1829 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00001830
Evan Cheng80e89d72006-02-14 09:11:59 +00001831 if (VT > LVT)
1832 VT = LVT;
1833
Evan Chengdea72452006-02-14 23:05:54 +00001834 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00001835 while (Size != 0) {
1836 unsigned VTSize = getSizeInBits(VT) / 8;
1837 while (VTSize > Size) {
1838 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001839 VTSize >>= 1;
1840 }
Evan Cheng80e89d72006-02-14 09:11:59 +00001841 assert(MVT::isInteger(VT));
1842
1843 if (++NumMemOps > Limit)
1844 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00001845 MemOps.push_back(VT);
1846 Size -= VTSize;
1847 }
Evan Cheng80e89d72006-02-14 09:11:59 +00001848
1849 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00001850}
1851
Chris Lattner7041ee32005-01-11 05:56:49 +00001852void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001853 SDOperand Op1 = getValue(I.getOperand(1));
1854 SDOperand Op2 = getValue(I.getOperand(2));
1855 SDOperand Op3 = getValue(I.getOperand(3));
1856 SDOperand Op4 = getValue(I.getOperand(4));
1857 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1858 if (Align == 0) Align = 1;
1859
1860 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1861 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00001862
1863 // Expand memset / memcpy to a series of load / store ops
1864 // if the size operand falls below a certain threshold.
1865 std::vector<SDOperand> OutChains;
1866 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00001867 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00001868 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00001869 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1870 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00001871 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00001872 unsigned Offset = 0;
1873 for (unsigned i = 0; i < NumMemOps; i++) {
1874 MVT::ValueType VT = MemOps[i];
1875 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00001876 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengc080d6f2006-02-15 01:54:51 +00001877 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1878 Value,
Chris Lattner864635a2006-02-22 22:37:12 +00001879 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1880 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chengc080d6f2006-02-15 01:54:51 +00001881 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00001882 Offset += VTSize;
1883 }
Evan Cheng1db92f92006-02-14 08:22:34 +00001884 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001885 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00001886 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001887 case ISD::MEMCPY: {
1888 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1889 Size->getValue(), Align, TLI)) {
1890 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00001891 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001892 GlobalAddressSDNode *G = NULL;
1893 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00001894 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001895
1896 if (Op2.getOpcode() == ISD::GlobalAddress)
1897 G = cast<GlobalAddressSDNode>(Op2);
1898 else if (Op2.getOpcode() == ISD::ADD &&
1899 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1900 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1901 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00001902 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00001903 }
1904 if (G) {
1905 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengcffbb512006-02-16 23:11:42 +00001906 if (GV) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00001907 Str = getStringValue(GV);
Evan Chengcffbb512006-02-16 23:11:42 +00001908 if (!Str.empty()) {
1909 CopyFromStr = true;
1910 SrcOff += SrcDelta;
1911 }
1912 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00001913 }
1914
Evan Chengc080d6f2006-02-15 01:54:51 +00001915 for (unsigned i = 0; i < NumMemOps; i++) {
1916 MVT::ValueType VT = MemOps[i];
1917 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001918 SDOperand Value, Chain, Store;
1919
Evan Chengcffbb512006-02-16 23:11:42 +00001920 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00001921 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1922 Chain = getRoot();
1923 Store =
1924 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1925 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1926 DAG.getSrcValue(I.getOperand(1), DstOff));
1927 } else {
1928 Value = DAG.getLoad(VT, getRoot(),
1929 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1930 DAG.getSrcValue(I.getOperand(2), SrcOff));
1931 Chain = Value.getValue(1);
1932 Store =
1933 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1934 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1935 DAG.getSrcValue(I.getOperand(1), DstOff));
1936 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001937 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00001938 SrcOff += VTSize;
1939 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00001940 }
1941 }
1942 break;
1943 }
1944 }
1945
1946 if (!OutChains.empty()) {
1947 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
1948 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00001949 }
1950 }
1951
Chris Lattner7041ee32005-01-11 05:56:49 +00001952 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00001953 Ops.push_back(getRoot());
Evan Cheng1db92f92006-02-14 08:22:34 +00001954 Ops.push_back(Op1);
1955 Ops.push_back(Op2);
1956 Ops.push_back(Op3);
1957 Ops.push_back(Op4);
Chris Lattner7041ee32005-01-11 05:56:49 +00001958 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00001959}
1960
Chris Lattner7041ee32005-01-11 05:56:49 +00001961//===----------------------------------------------------------------------===//
1962// SelectionDAGISel code
1963//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00001964
1965unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1966 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1967}
1968
Chris Lattner495a0b52005-08-17 06:37:43 +00001969void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00001970 // FIXME: we only modify the CFG to split critical edges. This
1971 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00001972}
Chris Lattner1c08c712005-01-07 07:47:53 +00001973
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001974
1975/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1976/// casting to the type of GEPI.
1977static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1978 Value *Ptr, Value *PtrOffset) {
1979 if (V) return V; // Already computed.
1980
1981 BasicBlock::iterator InsertPt;
1982 if (BB == GEPI->getParent()) {
1983 // If insert into the GEP's block, insert right after the GEP.
1984 InsertPt = GEPI;
1985 ++InsertPt;
1986 } else {
1987 // Otherwise, insert at the top of BB, after any PHI nodes
1988 InsertPt = BB->begin();
1989 while (isa<PHINode>(InsertPt)) ++InsertPt;
1990 }
1991
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001992 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1993 // BB so that there is only one value live across basic blocks (the cast
1994 // operand).
1995 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1996 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1997 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1998
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001999 // Add the offset, cast it to the right type.
2000 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2001 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2002 return V = Ptr;
2003}
2004
2005
2006/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2007/// selection, we want to be a bit careful about some things. In particular, if
2008/// we have a GEP instruction that is used in a different block than it is
2009/// defined, the addressing expression of the GEP cannot be folded into loads or
2010/// stores that use it. In this case, decompose the GEP and move constant
2011/// indices into blocks that use it.
2012static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2013 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002014 // If this GEP is only used inside the block it is defined in, there is no
2015 // need to rewrite it.
2016 bool isUsedOutsideDefBB = false;
2017 BasicBlock *DefBB = GEPI->getParent();
2018 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2019 UI != E; ++UI) {
2020 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2021 isUsedOutsideDefBB = true;
2022 break;
2023 }
2024 }
2025 if (!isUsedOutsideDefBB) return;
2026
2027 // If this GEP has no non-zero constant indices, there is nothing we can do,
2028 // ignore it.
2029 bool hasConstantIndex = false;
2030 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2031 E = GEPI->op_end(); OI != E; ++OI) {
2032 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2033 if (CI->getRawValue()) {
2034 hasConstantIndex = true;
2035 break;
2036 }
2037 }
Chris Lattner3802c252005-12-11 09:05:13 +00002038 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2039 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002040
2041 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2042 // constant offset (which we now know is non-zero) and deal with it later.
2043 uint64_t ConstantOffset = 0;
2044 const Type *UIntPtrTy = TD.getIntPtrType();
2045 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2046 const Type *Ty = GEPI->getOperand(0)->getType();
2047
2048 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2049 E = GEPI->op_end(); OI != E; ++OI) {
2050 Value *Idx = *OI;
2051 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2052 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2053 if (Field)
2054 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2055 Ty = StTy->getElementType(Field);
2056 } else {
2057 Ty = cast<SequentialType>(Ty)->getElementType();
2058
2059 // Handle constant subscripts.
2060 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2061 if (CI->getRawValue() == 0) continue;
2062
2063 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2064 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2065 else
2066 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2067 continue;
2068 }
2069
2070 // Ptr = Ptr + Idx * ElementSize;
2071
2072 // Cast Idx to UIntPtrTy if needed.
2073 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2074
2075 uint64_t ElementSize = TD.getTypeSize(Ty);
2076 // Mask off bits that should not be set.
2077 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2078 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2079
2080 // Multiply by the element size and add to the base.
2081 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2082 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2083 }
2084 }
2085
2086 // Make sure that the offset fits in uintptr_t.
2087 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2088 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2089
2090 // Okay, we have now emitted all of the variable index parts to the BB that
2091 // the GEP is defined in. Loop over all of the using instructions, inserting
2092 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002093 // instruction to use the newly computed value, making GEPI dead. When the
2094 // user is a load or store instruction address, we emit the add into the user
2095 // block, otherwise we use a canonical version right next to the gep (these
2096 // won't be foldable as addresses, so we might as well share the computation).
2097
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002098 std::map<BasicBlock*,Value*> InsertedExprs;
2099 while (!GEPI->use_empty()) {
2100 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002101
2102 // If this use is not foldable into the addressing mode, use a version
2103 // emitted in the GEP block.
2104 Value *NewVal;
2105 if (!isa<LoadInst>(User) &&
2106 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2107 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2108 Ptr, PtrOffset);
2109 } else {
2110 // Otherwise, insert the code in the User's block so it can be folded into
2111 // any users in that block.
2112 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002113 User->getParent(), GEPI,
2114 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002115 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002116 User->replaceUsesOfWith(GEPI, NewVal);
2117 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002118
2119 // Finally, the GEP is dead, remove it.
2120 GEPI->eraseFromParent();
2121}
2122
Chris Lattner1c08c712005-01-07 07:47:53 +00002123bool SelectionDAGISel::runOnFunction(Function &Fn) {
2124 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2125 RegMap = MF.getSSARegMap();
2126 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2127
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002128 // First, split all critical edges for PHI nodes with incoming values that are
2129 // constants, this way the load of the constant into a vreg will not be placed
2130 // into MBBs that are used some other way.
2131 //
2132 // In this pass we also look for GEP instructions that are used across basic
2133 // blocks and rewrites them to improve basic-block-at-a-time selection.
2134 //
Chris Lattner36b708f2005-08-18 17:35:14 +00002135 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2136 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002137 BasicBlock::iterator BBI;
2138 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00002139 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2140 if (isa<Constant>(PN->getIncomingValue(i)))
2141 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002142
2143 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2144 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2145 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00002146 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002147
Chris Lattner1c08c712005-01-07 07:47:53 +00002148 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2149
2150 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2151 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00002152
Chris Lattner1c08c712005-01-07 07:47:53 +00002153 return true;
2154}
2155
2156
Chris Lattnerddb870b2005-01-13 17:59:43 +00002157SDOperand SelectionDAGISel::
2158CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002159 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00002160 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002161 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00002162 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002163
2164 // If this type is not legal, we must make sure to not create an invalid
2165 // register use.
2166 MVT::ValueType SrcVT = Op.getValueType();
2167 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2168 SelectionDAG &DAG = SDL.DAG;
2169 if (SrcVT == DestVT) {
2170 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2171 } else if (SrcVT < DestVT) {
2172 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00002173 if (MVT::isFloatingPoint(SrcVT))
2174 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2175 else
Chris Lattnerfab08872005-09-02 00:19:37 +00002176 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002177 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2178 } else {
2179 // The src value is expanded into multiple registers.
2180 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2181 Op, DAG.getConstant(0, MVT::i32));
2182 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2183 Op, DAG.getConstant(1, MVT::i32));
2184 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2185 return DAG.getCopyToReg(Op, Reg+1, Hi);
2186 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002187}
2188
Chris Lattner068a81e2005-01-17 17:15:02 +00002189void SelectionDAGISel::
2190LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2191 std::vector<SDOperand> &UnorderedChains) {
2192 // If this is the entry block, emit arguments.
2193 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00002194 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00002195 SDOperand OldRoot = SDL.DAG.getRoot();
2196 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00002197
Chris Lattnerbf209482005-10-30 19:42:35 +00002198 unsigned a = 0;
2199 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2200 AI != E; ++AI, ++a)
2201 if (!AI->use_empty()) {
2202 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00002203
Chris Lattnerbf209482005-10-30 19:42:35 +00002204 // If this argument is live outside of the entry block, insert a copy from
2205 // whereever we got it to the vreg that other BB's will reference it as.
2206 if (FuncInfo.ValueMap.count(AI)) {
2207 SDOperand Copy =
2208 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2209 UnorderedChains.push_back(Copy);
2210 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00002211 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002212
2213 // Next, if the function has live ins that need to be copied into vregs,
2214 // emit the copies now, into the top of the block.
2215 MachineFunction &MF = SDL.DAG.getMachineFunction();
2216 if (MF.livein_begin() != MF.livein_end()) {
2217 SSARegMap *RegMap = MF.getSSARegMap();
2218 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2219 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2220 E = MF.livein_end(); LI != E; ++LI)
2221 if (LI->second)
2222 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2223 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00002224 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002225
2226 // Finally, if the target has anything special to do, allow it to do so.
2227 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00002228}
2229
2230
Chris Lattner1c08c712005-01-07 07:47:53 +00002231void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2232 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2233 FunctionLoweringInfo &FuncInfo) {
2234 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002235
2236 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002237
Chris Lattnerbf209482005-10-30 19:42:35 +00002238 // Lower any arguments needed in this block if this is the entry block.
2239 if (LLVMBB == &LLVMBB->getParent()->front())
2240 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00002241
2242 BB = FuncInfo.MBBMap[LLVMBB];
2243 SDL.setCurrentBasicBlock(BB);
2244
2245 // Lower all of the non-terminator instructions.
2246 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2247 I != E; ++I)
2248 SDL.visit(*I);
2249
2250 // Ensure that all instructions which are used outside of their defining
2251 // blocks are available as virtual registers.
2252 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002253 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00002254 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00002255 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00002256 UnorderedChains.push_back(
2257 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00002258 }
2259
2260 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2261 // ensure constants are generated when needed. Remember the virtual registers
2262 // that need to be added to the Machine PHI nodes as input. We cannot just
2263 // directly add them, because expansion might result in multiple MBB's for one
2264 // BB. As such, the start of the BB might correspond to a different MBB than
2265 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00002266 //
Chris Lattner1c08c712005-01-07 07:47:53 +00002267
2268 // Emit constants only once even if used by multiple PHI nodes.
2269 std::map<Constant*, unsigned> ConstantsOut;
2270
2271 // Check successor nodes PHI nodes that expect a constant to be available from
2272 // this block.
2273 TerminatorInst *TI = LLVMBB->getTerminator();
2274 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2275 BasicBlock *SuccBB = TI->getSuccessor(succ);
2276 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2277 PHINode *PN;
2278
2279 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2280 // nodes and Machine PHI nodes, but the incoming operands have not been
2281 // emitted yet.
2282 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00002283 (PN = dyn_cast<PHINode>(I)); ++I)
2284 if (!PN->use_empty()) {
2285 unsigned Reg;
2286 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2287 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2288 unsigned &RegOut = ConstantsOut[C];
2289 if (RegOut == 0) {
2290 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002291 UnorderedChains.push_back(
2292 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00002293 }
2294 Reg = RegOut;
2295 } else {
2296 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00002297 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00002298 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00002299 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2300 "Didn't codegen value into a register!??");
2301 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002302 UnorderedChains.push_back(
2303 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00002304 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002305 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002306
Chris Lattnerf44fd882005-01-07 21:34:19 +00002307 // Remember that this register needs to added to the machine PHI node as
2308 // the input for this MBB.
2309 unsigned NumElements =
2310 TLI.getNumElements(TLI.getValueType(PN->getType()));
2311 for (unsigned i = 0, e = NumElements; i != e; ++i)
2312 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00002313 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002314 }
2315 ConstantsOut.clear();
2316
Chris Lattnerddb870b2005-01-13 17:59:43 +00002317 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00002318 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00002319 SDOperand Root = SDL.getRoot();
2320 if (Root.getOpcode() != ISD::EntryToken) {
2321 unsigned i = 0, e = UnorderedChains.size();
2322 for (; i != e; ++i) {
2323 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2324 if (UnorderedChains[i].Val->getOperand(0) == Root)
2325 break; // Don't add the root if we already indirectly depend on it.
2326 }
2327
2328 if (i == e)
2329 UnorderedChains.push_back(Root);
2330 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00002331 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2332 }
2333
Chris Lattner1c08c712005-01-07 07:47:53 +00002334 // Lower the terminator after the copies are emitted.
2335 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00002336
2337 // Make sure the root of the DAG is up-to-date.
2338 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00002339}
2340
2341void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2342 FunctionLoweringInfo &FuncInfo) {
Jim Laskeyb2efb852006-01-04 22:28:25 +00002343 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner1c08c712005-01-07 07:47:53 +00002344 CurDAG = &DAG;
2345 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2346
2347 // First step, lower LLVM code to some DAG. This DAG may use operations and
2348 // types that are not supported by the target.
2349 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2350
Chris Lattneraf21d552005-10-10 16:47:10 +00002351 // Run the DAG combiner in pre-legalize mode.
2352 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00002353
Chris Lattner1c08c712005-01-07 07:47:53 +00002354 DEBUG(std::cerr << "Lowered selection DAG:\n");
2355 DEBUG(DAG.dump());
2356
2357 // Second step, hack on the DAG until it only uses operations and types that
2358 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00002359 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00002360
2361 DEBUG(std::cerr << "Legalized selection DAG:\n");
2362 DEBUG(DAG.dump());
2363
Chris Lattneraf21d552005-10-10 16:47:10 +00002364 // Run the DAG combiner in post-legalize mode.
2365 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00002366
Evan Chenga9c20912006-01-21 02:32:06 +00002367 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattnerd48050a2005-10-05 06:09:10 +00002368
Chris Lattnera33ef482005-03-30 01:10:47 +00002369 // Third, instruction select all of the operations to machine code, adding the
2370 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00002371 InstructionSelectBasicBlock(DAG);
2372
Chris Lattner1c08c712005-01-07 07:47:53 +00002373 DEBUG(std::cerr << "Selected machine code:\n");
2374 DEBUG(BB->dump());
2375
Chris Lattnera33ef482005-03-30 01:10:47 +00002376 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00002377 // PHI nodes in successors.
2378 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2379 MachineInstr *PHI = PHINodesToUpdate[i].first;
2380 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2381 "This is not a machine PHI node that we are updating!");
2382 PHI->addRegOperand(PHINodesToUpdate[i].second);
2383 PHI->addMachineBasicBlockOperand(BB);
2384 }
Chris Lattnera33ef482005-03-30 01:10:47 +00002385
2386 // Finally, add the CFG edges from the last selected MBB to the successor
2387 // MBBs.
2388 TerminatorInst *TI = LLVMBB->getTerminator();
2389 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2390 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2391 BB->addSuccessor(Succ0MBB);
2392 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002393}
Evan Chenga9c20912006-01-21 02:32:06 +00002394
2395//===----------------------------------------------------------------------===//
2396/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2397/// target node in the graph.
2398void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2399 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00002400 ScheduleDAG *SL = NULL;
2401
2402 switch (ISHeuristic) {
2403 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Cheng3f239522006-01-25 09:12:57 +00002404 case defaultScheduling:
2405 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2406 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2407 else /* TargetLowering::SchedulingForRegPressure */
2408 SL = createBURRListDAGScheduler(DAG, BB);
2409 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002410 case noScheduling:
2411 case simpleScheduling:
2412 case simpleNoItinScheduling:
2413 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
2414 break;
Evan Chengf0f9c902006-01-23 08:26:10 +00002415 case listSchedulingBURR:
2416 SL = createBURRListDAGScheduler(DAG, BB);
Evan Cheng4ef10862006-01-23 07:01:07 +00002417 }
Chris Lattnera3818e62006-01-21 19:12:11 +00002418 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00002419 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00002420}