1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Aggregate Expr nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CodeGenModule.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/StmtVisitor.h" 18 #include "llvm/Constants.h" 19 #include "llvm/Function.h" 20 #include "llvm/GlobalVariable.h" 21 #include "llvm/Support/Compiler.h" 22 #include "llvm/Intrinsics.h" 23 using namespace clang; 24 using namespace CodeGen; 25 26 //===----------------------------------------------------------------------===// 27 // Aggregate Expression Emitter 28 //===----------------------------------------------------------------------===// 29 30 namespace { 31 class VISIBILITY_HIDDEN AggExprEmitter : public StmtVisitor<AggExprEmitter> { 32 CodeGenFunction &CGF; 33 llvm::IRBuilder<> &Builder; 34 llvm::Value *DestPtr; 35 bool VolatileDest; 36 public: 37 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool volatileDest) 38 : CGF(cgf), Builder(CGF.Builder), 39 DestPtr(destPtr), VolatileDest(volatileDest) { 40 } 41 42 //===--------------------------------------------------------------------===// 43 // Utilities 44 //===--------------------------------------------------------------------===// 45 46 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 47 /// represents a value lvalue, this method emits the address of the lvalue, 48 /// then loads the result into DestPtr. 49 void EmitAggLoadOfLValue(const Expr *E); 50 51 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 52 QualType EltTy); 53 54 void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty); 55 56 void EmitNonConstInit(InitListExpr *E); 57 58 //===--------------------------------------------------------------------===// 59 // Visitor Methods 60 //===--------------------------------------------------------------------===// 61 62 void VisitStmt(Stmt *S) { 63 CGF.ErrorUnsupported(S, "aggregate expression"); 64 } 65 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 66 67 // l-values. 68 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 69 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 70 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 71 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 72 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) 73 { EmitAggLoadOfLValue(E); } 74 75 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 76 EmitAggLoadOfLValue(E); 77 } 78 79 // Operators. 80 // case Expr::UnaryOperatorClass: 81 // case Expr::CastExprClass: 82 void VisitImplicitCastExpr(ImplicitCastExpr *E); 83 void VisitCallExpr(const CallExpr *E); 84 void VisitStmtExpr(const StmtExpr *E); 85 void VisitBinaryOperator(const BinaryOperator *BO); 86 void VisitBinAssign(const BinaryOperator *E); 87 void VisitOverloadExpr(const OverloadExpr *E); 88 void VisitBinComma(const BinaryOperator *E); 89 90 void VisitObjCMessageExpr(ObjCMessageExpr *E); 91 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 92 EmitAggLoadOfLValue(E); 93 } 94 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 95 96 void VisitConditionalOperator(const ConditionalOperator *CO); 97 void VisitInitListExpr(InitListExpr *E); 98 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 99 Visit(DAE->getExpr()); 100 } 101 void VisitVAArgExpr(VAArgExpr *E); 102 103 void EmitInitializationToLValue(Expr *E, LValue Address); 104 void EmitNullInitializationToLValue(LValue Address, QualType T); 105 // case Expr::ChooseExprClass: 106 107 }; 108 } // end anonymous namespace. 109 110 //===----------------------------------------------------------------------===// 111 // Utilities 112 //===----------------------------------------------------------------------===// 113 114 void AggExprEmitter::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) { 115 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 116 117 // Aggregate assignment turns into llvm.memset. 118 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 119 if (DestPtr->getType() != BP) 120 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 121 122 // Get size and alignment info for this aggregate. 123 std::pair<uint64_t, unsigned> TypeInfo = CGF.getContext().getTypeInfo(Ty); 124 125 // FIXME: Handle variable sized types. 126 const llvm::Type *IntPtr = llvm::IntegerType::get(CGF.LLVMPointerWidth); 127 128 llvm::Value *MemSetOps[4] = { 129 DestPtr, 130 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty), 131 // TypeInfo.first describes size in bits. 132 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 133 llvm::ConstantInt::get(llvm::Type::Int32Ty, TypeInfo.second/8) 134 }; 135 136 Builder.CreateCall(CGF.CGM.getMemSetFn(), MemSetOps, MemSetOps+4); 137 } 138 139 void AggExprEmitter::EmitAggregateCopy(llvm::Value *DestPtr, 140 llvm::Value *SrcPtr, QualType Ty) { 141 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 142 143 // Aggregate assignment turns into llvm.memmove. 144 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 145 if (DestPtr->getType() != BP) 146 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 147 if (SrcPtr->getType() != BP) 148 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 149 150 // Get size and alignment info for this aggregate. 151 std::pair<uint64_t, unsigned> TypeInfo = CGF.getContext().getTypeInfo(Ty); 152 153 // FIXME: Handle variable sized types. 154 const llvm::Type *IntPtr = llvm::IntegerType::get(CGF.LLVMPointerWidth); 155 156 llvm::Value *MemMoveOps[4] = { 157 DestPtr, SrcPtr, 158 // TypeInfo.first describes size in bits. 159 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 160 llvm::ConstantInt::get(llvm::Type::Int32Ty, TypeInfo.second/8) 161 }; 162 163 Builder.CreateCall(CGF.CGM.getMemMoveFn(), MemMoveOps, MemMoveOps+4); 164 } 165 166 167 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 168 /// represents a value lvalue, this method emits the address of the lvalue, 169 /// then loads the result into DestPtr. 170 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 171 LValue LV = CGF.EmitLValue(E); 172 assert(LV.isSimple() && "Can't have aggregate bitfield, vector, etc"); 173 llvm::Value *SrcPtr = LV.getAddress(); 174 175 // If the result is ignored, don't copy from the value. 176 if (DestPtr == 0) 177 // FIXME: If the source is volatile, we must read from it. 178 return; 179 180 EmitAggregateCopy(DestPtr, SrcPtr, E->getType()); 181 } 182 183 //===----------------------------------------------------------------------===// 184 // Visitor Methods 185 //===----------------------------------------------------------------------===// 186 187 void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E) { 188 assert(CGF.getContext().typesAreCompatible( 189 E->getSubExpr()->getType().getUnqualifiedType(), 190 E->getType().getUnqualifiedType()) && 191 "Implicit cast types must be compatible"); 192 Visit(E->getSubExpr()); 193 } 194 195 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 196 RValue RV = CGF.EmitCallExpr(E); 197 assert(RV.isAggregate() && "Return value must be aggregate value!"); 198 199 // If the result is ignored, don't copy from the value. 200 if (DestPtr == 0) 201 // FIXME: If the source is volatile, we must read from it. 202 return; 203 204 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 205 } 206 207 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 208 RValue RV = CGF.EmitObjCMessageExpr(E); 209 assert(RV.isAggregate() && "Return value must be aggregate value!"); 210 211 // If the result is ignored, don't copy from the value. 212 if (DestPtr == 0) 213 // FIXME: If the source is volatile, we must read from it. 214 return; 215 216 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 217 } 218 219 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 220 RValue RV = CGF.EmitObjCPropertyGet(E); 221 assert(RV.isAggregate() && "Return value must be aggregate value!"); 222 223 // If the result is ignored, don't copy from the value. 224 if (DestPtr == 0) 225 // FIXME: If the source is volatile, we must read from it. 226 return; 227 228 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 229 } 230 231 void AggExprEmitter::VisitOverloadExpr(const OverloadExpr *E) { 232 RValue RV = CGF.EmitCallExpr(E->getFn(), E->arg_begin(), 233 E->arg_end(CGF.getContext())); 234 235 assert(RV.isAggregate() && "Return value must be aggregate value!"); 236 237 // If the result is ignored, don't copy from the value. 238 if (DestPtr == 0) 239 // FIXME: If the source is volatile, we must read from it. 240 return; 241 242 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 243 } 244 245 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 246 CGF.EmitAnyExpr(E->getLHS()); 247 CGF.EmitAggExpr(E->getRHS(), DestPtr, false); 248 } 249 250 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 251 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 252 } 253 254 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 255 CGF.ErrorUnsupported(E, "aggregate binary expression"); 256 } 257 258 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 259 // For an assignment to work, the value on the right has 260 // to be compatible with the value on the left. 261 assert(CGF.getContext().typesAreCompatible( 262 E->getLHS()->getType().getUnqualifiedType(), 263 E->getRHS()->getType().getUnqualifiedType()) 264 && "Invalid assignment"); 265 LValue LHS = CGF.EmitLValue(E->getLHS()); 266 267 // Codegen the RHS so that it stores directly into the LHS. 268 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), false /*FIXME: VOLATILE LHS*/); 269 270 if (DestPtr == 0) 271 return; 272 273 // If the result of the assignment is used, copy the RHS there also. 274 EmitAggregateCopy(DestPtr, LHS.getAddress(), E->getType()); 275 } 276 277 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 278 llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?"); 279 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:"); 280 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont"); 281 282 llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond()); 283 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock); 284 285 CGF.EmitBlock(LHSBlock); 286 287 // Handle the GNU extension for missing LHS. 288 assert(E->getLHS() && "Must have LHS for aggregate value"); 289 290 Visit(E->getLHS()); 291 Builder.CreateBr(ContBlock); 292 LHSBlock = Builder.GetInsertBlock(); 293 294 CGF.EmitBlock(RHSBlock); 295 296 Visit(E->getRHS()); 297 Builder.CreateBr(ContBlock); 298 RHSBlock = Builder.GetInsertBlock(); 299 300 CGF.EmitBlock(ContBlock); 301 } 302 303 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 304 llvm::Value *ArgValue = CGF.EmitLValue(VE->getSubExpr()).getAddress(); 305 llvm::Value *V = Builder.CreateVAArg(ArgValue, CGF.ConvertType(VE->getType())); 306 if (DestPtr) 307 // FIXME: volatility 308 Builder.CreateStore(V, DestPtr); 309 } 310 311 void AggExprEmitter::EmitNonConstInit(InitListExpr *E) { 312 313 const llvm::PointerType *APType = 314 cast<llvm::PointerType>(DestPtr->getType()); 315 const llvm::Type *DestType = APType->getElementType(); 316 317 if (const llvm::ArrayType *AType = dyn_cast<llvm::ArrayType>(DestType)) { 318 unsigned NumInitElements = E->getNumInits(); 319 320 unsigned i; 321 for (i = 0; i != NumInitElements; ++i) { 322 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 323 Expr *Init = E->getInit(i); 324 if (isa<InitListExpr>(Init)) 325 CGF.EmitAggExpr(Init, NextVal, VolatileDest); 326 else 327 // FIXME: volatility 328 Builder.CreateStore(CGF.EmitScalarExpr(Init), NextVal); 329 } 330 331 // Emit remaining default initializers 332 unsigned NumArrayElements = AType->getNumElements(); 333 QualType QType = E->getInit(0)->getType(); 334 const llvm::Type *EType = AType->getElementType(); 335 for (/*Do not initialize i*/; i < NumArrayElements; ++i) { 336 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 337 if (EType->isSingleValueType()) 338 // FIXME: volatility 339 Builder.CreateStore(llvm::Constant::getNullValue(EType), NextVal); 340 else 341 EmitAggregateClear(NextVal, QType); 342 } 343 } else 344 assert(false && "Invalid initializer"); 345 } 346 347 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) { 348 // FIXME: Are initializers affected by volatile? 349 if (E->getType()->isComplexType()) { 350 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 351 } else if (CGF.hasAggregateLLVMType(E->getType())) { 352 CGF.EmitAnyExpr(E, LV.getAddress(), false); 353 } else { 354 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType()); 355 } 356 } 357 358 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 359 if (!CGF.hasAggregateLLVMType(T)) { 360 // For non-aggregates, we can store zero 361 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 362 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 363 } else { 364 // Otherwise, just memset the whole thing to zero. This is legal 365 // because in LLVM, all default initializers are guaranteed to have a 366 // bit pattern of all zeros. 367 // There's a potential optimization opportunity in combining 368 // memsets; that would be easy for arrays, but relatively 369 // difficult for structures with the current code. 370 llvm::Value *MemSet = CGF.CGM.getIntrinsic(llvm::Intrinsic::memset_i64); 371 uint64_t Size = CGF.getContext().getTypeSize(T); 372 373 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 374 llvm::Value* DestPtr = Builder.CreateBitCast(LV.getAddress(), BP, "tmp"); 375 Builder.CreateCall4(MemSet, DestPtr, 376 llvm::ConstantInt::get(llvm::Type::Int8Ty, 0), 377 llvm::ConstantInt::get(llvm::Type::Int64Ty, Size/8), 378 llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 379 } 380 } 381 382 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 383 // FIXME: For constant expressions, call into const expr emitter so 384 // that we can emit a memcpy instead of storing the individual 385 // members. This is purely for perf; both codepaths lead to 386 // equivalent (although not necessarily identical) code. It's worth 387 // noting that LLVM keeps on getting smarter, though, so it might 388 // not be worth bothering. 389 390 // Handle initialization of an array. 391 if (E->getType()->isArrayType()) { 392 const llvm::PointerType *APType = 393 cast<llvm::PointerType>(DestPtr->getType()); 394 const llvm::ArrayType *AType = 395 cast<llvm::ArrayType>(APType->getElementType()); 396 397 uint64_t NumInitElements = E->getNumInits(); 398 399 if (E->getNumInits() > 0) { 400 QualType T1 = E->getType(); 401 QualType T2 = E->getInit(0)->getType(); 402 if (CGF.getContext().getCanonicalType(T1).getUnqualifiedType() == 403 CGF.getContext().getCanonicalType(T2).getUnqualifiedType()) { 404 EmitAggLoadOfLValue(E->getInit(0)); 405 return; 406 } 407 } 408 409 uint64_t NumArrayElements = AType->getNumElements(); 410 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 411 ElementType =CGF.getContext().getAsArrayType(ElementType)->getElementType(); 412 413 unsigned CVRqualifier = ElementType.getCVRQualifiers(); 414 415 for (uint64_t i = 0; i != NumArrayElements; ++i) { 416 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 417 if (i < NumInitElements) 418 EmitInitializationToLValue(E->getInit(i), 419 LValue::MakeAddr(NextVal, CVRqualifier)); 420 else 421 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, CVRqualifier), 422 ElementType); 423 } 424 return; 425 } 426 427 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 428 429 // Do struct initialization; this code just sets each individual member 430 // to the approprate value. This makes bitfield support automatic; 431 // the disadvantage is that the generated code is more difficult for 432 // the optimizer, especially with bitfields. 433 unsigned NumInitElements = E->getNumInits(); 434 RecordDecl *SD = E->getType()->getAsRecordType()->getDecl(); 435 unsigned NumMembers = SD->getNumMembers() - SD->hasFlexibleArrayMember(); 436 unsigned CurInitVal = 0; 437 bool isUnion = E->getType()->isUnionType(); 438 439 // Here we iterate over the fields; this makes it simpler to both 440 // default-initialize fields and skip over unnamed fields. 441 for (unsigned CurFieldNo = 0; CurFieldNo != NumMembers; ++CurFieldNo) { 442 FieldDecl *CurField = SD->getMember(CurFieldNo); 443 if (CurField->getIdentifier() == 0) { 444 // Initializers can't initialize unnamed fields, e.g. "int : 20;" 445 continue; 446 } 447 // FIXME: volatility 448 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, CurField, isUnion,0); 449 if (CurInitVal < NumInitElements) { 450 // Store the initializer into the field 451 // This will probably have to get a bit smarter when we support 452 // designators in initializers 453 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc); 454 } else { 455 // We're out of initalizers; default-initialize to null 456 EmitNullInitializationToLValue(FieldLoc, CurField->getType()); 457 } 458 459 // Unions only initialize one field. 460 // (things can get weird with designators, but they aren't 461 // supported yet.) 462 if (E->getType()->isUnionType()) 463 break; 464 } 465 } 466 467 //===----------------------------------------------------------------------===// 468 // Entry Points into this File 469 //===----------------------------------------------------------------------===// 470 471 /// EmitAggExpr - Emit the computation of the specified expression of 472 /// aggregate type. The result is computed into DestPtr. Note that if 473 /// DestPtr is null, the value of the aggregate expression is not needed. 474 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 475 bool VolatileDest) { 476 assert(E && hasAggregateLLVMType(E->getType()) && 477 "Invalid aggregate expression to emit"); 478 479 AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E)); 480 } 481